﻿//<reference path="/Scripts/References.js" />
//<reference path="/ScriptsG/en-us/DynaContentDynamic.js" />

//-----------------------------------------------------------------------------------
//Uses Advanced JavaScript outlining for Visual Studio 11 to activate Region handling
//-----------------------------------------------------------------------------------

//#region Local variables
var savedEvt;
var menuToToggleActivation;
var AddEditModeAdd = true;
var MenuItemAction = new Object();
var cmEditor;
var cmWhat; //What is edited : ["js","css","html"]
var cmChanged = false; //true if cmSourceObj.html() != cmEditor.getValue();
var cmInitialContent; //Filled with initial code content when codemirror instanciated
var cmDenyPromptCMChange = false;
var codePannelResizing;
var tLayoutCodeMirror = new Array();
var layoutCodeMirrorHtml;
var layoutCodeMirrorCss;
var ribbonTabCount = 7;
var enRibbonTabs = { "_00Start": 0, "_01Insert": 1, "_02Layout": 2, "_03Code": 3, "_04Image": 4, "_05Table": 5, "_06Settings": 6 };
var LayoutHandlingDragHOriginalWith;
var LayoutHandlingDragVOriginalHeight;
var layoutHandlesCounter;
var reloadStyleQueryString;
//#endregion

//#region TinyMCE variables
var tinyMCEElements = "";
//#endregion

//#region Gridster variables
var gridster;
var gridsterEditorCSSExtension = "";
var gridsterMarginLeft = 10;
var gridsterMarginTop = 10;
var gridsterWidget_base_width = 20;
var gridsterWidget_base_height = 20;
var gridsterLayoutSlotDropHtml = '<div class="ui-icon ui-icon-trash layoutSlotDrop"></div>';
var gridsterLayoutSlotToDrop = null;
//#endregion

//#region UI State variables
var currentTabIndex = 0;
var lastLayoutSlotId = "";
var tinyMCELastElements = "divFooEditor";
//#endregion

//#region UseMode

var enUseModes = {
    "contentEditMode": "contentEditMode",
    "contentLayoutMode": "contentLayoutMode",
    "contentCodeMode": "contentCodeMode",
    "siteLayoutMode": "siteLayoutMode",
    "structureEditMode": "structureEditMode",
    "settingsMode": "settingsMode"
};

var UseMode = {
    current: enUseModes.contentEditMode,
    getCurrent: function () {
        return this.current;
    },
    setCurrent: function (value) {
        $("body").removeClass(this.current);
        this.current = value;
        $("body").addClass(this.current);
        console.log("UseMode:" + this.current);
        $("#te-panel").css("display", "none");
        switch (this.current) {
            case enUseModes.structureEditMode:
                $.fn.CodeMirrorPanelRemove();
                $.fn.TinyMCEShow(false);
                $.fn.ContentLayoutGridsterShow(false);
                $.fn.SettingsSiteLayoutHandlesShow(false);
                $.fn.AdminSettingsLayoutDisplayHandlesAndUploadButtons(false);
                break;
            case enUseModes.contentEditMode:
                $.fn.CodeMirrorPanelRemove();
                $.fn.ContentLayoutGridsterShow(false);
                $.fn.SettingsSiteLayoutHandlesShow(false);
                $.fn.AdminSettingsLayoutDisplayHandlesAndUploadButtons(false);
                break;
            case enUseModes.contentLayoutMode:
                $.fn.CodeMirrorPanelRemove();
                $.fn.TinyMCEShow(false);
                $.fn.ContentLayoutGridsterShow(true);
                $.fn.SettingsSiteLayoutHandlesShow(false);
                $.fn.AdminSettingsLayoutDisplayHandlesAndUploadButtons(false);
                break;
            case enUseModes.contentCodeMode:
                $.fn.TinyMCEShow(false);
                $.fn.ContentLayoutGridsterShow(false);
                $.fn.SettingsSiteLayoutHandlesShow(false);
                $.fn.AdminSettingsLayoutDisplayHandlesAndUploadButtons(false);
                break;
            case enUseModes.settingsMode:
                $.fn.CodeMirrorPanelRemove();
                $.fn.TinyMCEShow(false);
                $.fn.ContentLayoutGridsterShow(false);
                $.fn.SettingsSiteLayoutHandlesShow(false);
                $.fn.AdminSettingsLayoutDisplayHandlesAndUploadButtons(false);
                break;
            case enUseModes.siteLayoutMode:
                $.fn.CodeMirrorPanelRemove();
                $.fn.TinyMCEShow(false);
                $.fn.ContentLayoutGridsterShow(false);
                $.fn.SettingsSiteLayoutHandlesShow(true);
                $.fn.AdminSettingsLayoutDisplayHandlesAndUploadButtons(true);
                break;
        }
    }
};


//#endregion

//#region DocReady

$.fn.DocReady = function () {
    /// <summary>
    /// Scripts to execute when all page is loaded
    /// </summary>
    language = $("#hidLanguage").val();
    tpLang = uiLanguage.substr(0, 2);
    if (tpLang != 'en') {
        //$.timepicker.setDefaults($.timepicker.regional[tpLang]);
    }
    $("body").addClass("adminMode");
    $.fn.PrepareLayoutMenus(); //_layout.js
    $("#divMceRibbonBarPlaceholder").removeClass("notDisplayed");
    $(".AddMenuItem").on("click", $.fn.StructureEditorMenuItemAddEditDialog);
    $(".EditMenuItem").on("click", $.fn.StructureEditorMenuItemAddEditDialog);
    $(".RemoveMenuItem").on("click", $.fn.StructureEditorMenuItemRemoveConfirm);
    $(".Reorder").on("click", $.fn.StructureEditorMenuItemMove);
    $(".AdminModeMenuToggleActivation").on("click", $.fn.StructureEditorToggleActivationConfirmation);
    if (tpLang != 'en') {
        $(".datepicker").datetimepicker();
    }
    $("select").kendoDropDownList();
    $(".k-dropdown").css("width", 566);
    $("#divStructurePage .k-dropdown").css("width", 160);
    tLanguages = Languages.split(",");
    $.fn.TinyMCECreateTinyMCEInstance();
    $.fn.TinyMCEShow(false);
    $.fn.EditionBindLayoutSlotsClick();
    UseMode.setCurrent(enUseModes.contentEditMode);
}

//#endregion

//#region TinyMCE stuff

$.fn.TinyMCECreateTinyMCEInstance = function () {
    /// <summary>
    /// Creates the Tiny MCE instance
    /// </summary>
    var editorLang = uiLanguage.substring(0, 2);
    if ($("#divFooEditor").length == 0) {
        var htmlBribe = "<div id='divFooEditor' class='notDisplayed' >&nbsp;</div>";
        $("body").append(htmlBribe);
    }
    if (tinyMCEElements == undefined) {
        editorWidth = 0;
        editorHeight = 0;
    } else {
        if (tinyMCEElements == "divFooEditor") {
            editorWidth = 0;
            editorHeight = 0;
        } else {
            var element = $("#" + tinyMCEElements);
            editorWidth = element.width();
            editorHeight = element.height();
        }
    }
    //Remove any instance
    /*
    while (tinyMCE.editors.length > 0) {
        tinyMCE.execCommand('mceRemoveControl', false, tinymce.editors[0].id);
    }
    */
    tinyMCE.init
    (
        {
            // General options
            elements: tinyMCEElements,
            mode: "exact",
            language: editorLang,
            theme: "ribbon",
            plugins: "inlinepopups,tabfocus,advimagescale,loremipsum,image_tools,embed,tableextras,style,table,searchreplace,contextmenu,paste,wordcount,advlist,autosave,save,layer,table",//,noneditable,visualblocks",
            //inlinepopups_skin: 'ribbon_popup',
            theme_ribbon_fonts: "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats,Boing=kids_boing",
            noneditable_leave_contenteditable: false,
            width: editorWidth,
            height: editorHeight,
            // Theme options WARNING No space in tab caption
            theme_ribbon_tab1: {
                title: cap_Ribbon_Tab01_Start,
                items:
                [
                    ["innoToggleEdit_Tab00"],
                    ["innoSave_Tab00"],
                    ["paste"],
                    ["cut,copy", "|", "pastetext,pasteword"],
                    ["justifyleft,justifycenter,justifyright,justifyfull,mce_sup",
                        "outdent,numlist,forecolor",
                        "|",
                        "bold,italic,underline,strikethrough,mce_sub",
                        "indent,bullist,backcolor"],
                    ["paragraph", "heading1", "heading2", "heading3", "heading4", "heading5", "heading6"],
                    ["styleselect", "|", "fontselect", "|", "fontsizeselect"],
                    ["search", "|", "replace", "|", "removeformat"],
                ]
            },
            theme_ribbon_tab2: {
                title: cap_Ribbon_Tab02_Insert,
                items:
                [
                    ["innoToggleEdit_Tab01"],
                    ["innoSave_Tab01"],
                    ["tabledraw"],
                    ["image", "bestandsbeheer_file", "bestandsbeheer_video", "bestandsbeheer_mp3"],
                    ["embed"],
                    ["link", "|", "unlink", "|", "anchor"],
                    ["loremipsum", "|", "charmap", "|", "hr"]
                ]
            },
            theme_ribbon_tab3: {
                title: cap_Ribbon_Tab03_Layout,
                items:
                [
                    ["innoToggleEdit_Tab02"],
                    ["innoSave_Tab02"],
                    ["insertlayer,moveforward", "|", "absolute,movebackward"],
                    ["innoInsertAddGridsterWidget", "innoInsertLayout01", "innoInsertLayout02H", "innoInsertLayout02V", "innoInsertLayout031", "innoInsertLayout032", "innoInsertLayout041", "innoInsertLayout042"],
                    ["innoPaddings", "innoMargins"]
                ]
            },
            theme_ribbon_tab4: {
                title: cap_Ribbon_Tab04_Code,
                items:
                [
                    ["innoToggleEdit_Tab03"],
                    ["innoSave_Tab03"],
                    ["innoSourceHTML", "innoSourceCSS"]
                ]
            },
            theme_ribbon_tab5: {
                title: cap_Ribbon_Tab05_Image,
                bind: "img",
                items:
                    [
                        ["innoToggleEdit_Tab04"],
                        ["innoSave_Tab04"],
                        ["image_float_left", "image_float_right", "image_float_none"],
                        ["image_alt"],
                        ["image_width_plus", "|", "image_width_min", "|", "image_width_original"],
                        ["image_edit", "|", "image_remove"]
                    ]
            },
            theme_ribbon_tab6: {
                title: cap_Ribbon_Tab06_Table,
                bind: "td",
                items:
                    [
                        ["innoToggleEdit_Tab05"],
                        ["innoSave_Tab05"],
                        ["delete_table"], ["delete_col", "|", "delete_row"],
                        ["col_before", "|", "col_after"],
                        ["row_before", "|", "row_after"]
                    ]
            },
            theme_ribbon_tab7: {
                title: cap_Ribbon_Tab07_Settings,
                items:
                [
                    ["innoToggleEdit_Tab06"],
                    ["innoSave_Tab06"],
                    ["innoGeneralSettings", "innoPlugIns"],
                    ["innoSiteLayout"], // "innoLayoutMenuTop", "innoLayoutMenuLeft", 
                    ["innoRoles", "innoUsers"],
                    ["innoFilesManagement"]
                ]
            },
            //Absolute path WARNING
            //With URL Rewriting path mus be relative to root but not include authority.
            //The right setting for convert_url = false.
            remove_script_host: false,
            convert_urls: false,
            // Skin options
            //////////skin: "o2k7",
            //////////skin_variant: "silver",

            // Example content CSS (should be your site CSS)
            content_css: "/Content/EditableContent/Base.css?" + new Date().getTime(),

            //Drop lists for link/image/media/template dialogs
            //template_external_list_url: "js/template_list.js",
            //external_link_list_url: "js/link_list.js",
            //external_image_list_url: "js/image_list.js",
            //media_external_list_url: "js/media_list.js",

            file_browser_callback: "$.fn.TinyMCEFilebrowser",
            setup: $.fn.TinyMCERibbonCustomSetup
        }
    );
    //Detect Ribbon tab click
    $(".mce_innoSave").addClass("big");
}

$.fn.TinyMCEFilebrowser = function (field_name, url, type, win) {
    /// <summary>
    /// Tiny MCE File browser handler
    /// </summary>
    /// <param name="field_name"></param>
    /// <param name="url"></param>
    /// <param name="type"></param>
    /// <param name="win"></param>
    /// <returns type=""></returns>
    var fileBrowserURL = "/" + uiLanguage + "/finder";
    var sessionId = $("#hidSessionId").val();

    tinyMCE.activeEditor.windowManager.open({
        title: "Ajax File Manager",
        url: fileBrowserURL,
        width: 950,
        height: 650,
        inline: "yes",
        maximizable: "no",
        popup_css: false,
        close_previous: "yes"
    }, {
        window: win,
        input: field_name,
        sessionid: sessionId,
        resizable: "no"
    });
    return false;
}

$.fn.TinyMCEHideAllInstance = function () {
    /// <summary>
    /// Hide all tiny mce instances
    /// </summary>
    for (var i = 0; i < tinymce.editors.length; i++) {
        tinyMCE.get(tinymce.editors[i].id).hide();
    };
}

$.fn.TinyMCEInitTinyMCE = function (ed) {
    /// <summary>
    /// TinyMCE initialization
    /// </summary>
    /// <param name="ed">TinyMCE instance</param>
    var $ed = $("#" + ed.id + "_tbl");
    var $tbr = $ed.find("tr:nth(1)");
    var keepWidth = parseInt($ed.parent().parent().width());
    /*globals*/
    var $ifr = $("#" + ed.id + "_ifr");
    /**/

    $ifr.attr("marginwidth", "0");
    $ifr.attr("marginheight", "0");
    $ifr.css("margin", "0");
    $ifr.css("padding", "0");
    $ifr.css("background", "transparent");

    var divMceRibbonBarPlaceholderInitialHtml = '';
    divMceRibbonBarPlaceholderInitialHtml += '<span class="mceEditor defaultSkin">\n';
    divMceRibbonBarPlaceholderInitialHtml += '\t<table class="mceLayout">\n';
    divMceRibbonBarPlaceholderInitialHtml += '\t</table>\n';
    divMceRibbonBarPlaceholderInitialHtml += '</span>\n';
    $("#divMceRibbonBarPlaceholder").html(divMceRibbonBarPlaceholderInitialHtml);
    $rbnPH = $("#divMceRibbonBarPlaceholder").find("table");
    $ribbonTable = $("#divMceRibbonBarPlaceholder").find(":nth-child(1)").find(":nth-child(1)");
    $ribbonTable.css("width", "100%");
    $ribbonTable.css("margin-left", "0px");
    $ribbonTable.css("margin-right", "0px");
    $tbr.hide();
    $ed.css("width", keepWidth + "px");
    $ifr.css("width", keepWidth + "px");
    $rbnPH.append($tbr);
    $tbr.show();
    $(".AdminModeMenuButtonRight,.AdminModeMenuButtonLeft").css("display", "none");
    $.fn.TinyMCEInstanceInitialized();
    tinymce.execCommand('mceFocus', false, ed.id);

    //Advanced event handling
    tinymce.dom.Event.add(ed.getBody(), "blur", function (e) {

    });
}

$.fn.TinyMCEAddLayoutStyle = function () {
    /// <summary>
    /// Add layout green borders
    /// </summary>
    /// <param name="ed"></param>
    var ifr = $("#divFooEditor_ifr");

    var d = ifr[0].contentWindow.document;
    //d.open(); d.close();
    // now start doing normal jQuery:
    var editorSpecificStyles = "<style type='text/css' id='CSSExtension_ifr'>\n";
    editorSpecificStyles += "html, body {margin:0;padding:0;}\n";
    //editorSpecificStyles += ".ifrEditorFix {padding:5px;}\n";
    editorSpecificStyles += "</style>\n";
    if ($("head", d).find("#CSSExtension_ifr").length > 0) {
        $("head", d).find("#CSSExtension_ifr").remove();
    }
    $("head", d).append(editorSpecificStyles);
    $("body", d).removeClass("mceContentBody");
    //$("body", d).addClass("ifrEditorFix");

    //var ifrHtml = ifr.find("html");
    //var ifrHead = ifrHtml.find("head");
    //var ifrBody = ifr.find("#tinymce");

    //ifrHtml.css("height", "90%");
    //ifrBody.removeClass("mceContentBody");
    //ifrBody.addClass("ifrEditorFix");
}

$.fn.TinyMCEResizeActiveEditor = function (parent) {
    /// <summary>
    /// Resize TinyMCE Active editor width and/of height
    /// </summary>
    /// <param name="parent">resize editor to the parent size according to paddings</param>

    //Obsolete: divFooEditor is hidden during Site layouting

    //EditorWidth = parent.width();// - (layoutVar_divBodyPaddingLeft + layoutVar_divBodyPaddingRight);
    //EditorHeight = parent.height();// - layoutVar_divBodyPaddingTop - layoutVar_divBodyPaddingBottom - 50;
    //try {
    //    tinymce.EditorManager.activeEditor.theme.resizeTo(EditorWidth, EditorHeight);
    //} catch (e) { }
}

$.fn.TinyMCERibbonCustomSetup = function (ed) {
    /// <summary>
    /// Customization of TinyMCE Ribbon
    /// </summary>
    /// <param name="ed">TinyMCE Instance</param>

    ed.onKeyDown.add(function (ed, e) {
        var editedLayoutSlot = $("#" + lastLayoutSlotId);
        var nextLayoutSlotToEdit;

        switch (e.keyCode) {
            case 9: //Tab
                if (("#divContent .layoutSlot").length > 0) {
                    if (e.shiftKey) {
                        //Previous layoutSlot
                        nextLayoutSlotToEdit = editedLayoutSlot.closest("li").prev();
                        if (nextLayoutSlotToEdit.length == 0) {
                            nextLayoutSlotToEdit = editedLayoutSlot.closest("ul").children().last();
                        }
                    } else {
                        //Next layoutSlot
                        nextLayoutSlotToEdit = editedLayoutSlot.closest("li").next();
                        if (nextLayoutSlotToEdit.length == 0) {
                            nextLayoutSlotToEdit = editedLayoutSlot.closest("ul").children().first();
                        }
                    }
                }
                var nextLayoutSlotToEditId = nextLayoutSlotToEdit.find(".mceEditable").attr("id");
                $.fn.TinyMCEShow(true, nextLayoutSlotToEditId);
                //Scrolling
                $("#" + nextLayoutSlotToEditId).scrollintoview(true);
                e.preventDefault();
                return false;
                break;
        }
    });

    ed.onInit.add($.fn.TinyMCEInitTinyMCE);
    ed.onInit.add($.fn.TinyMCEAddLayoutStyle);
    // Add a custom button
    for (var i = 0; i < ribbonTabCount; i++) {
        ed.addButton
        (
            "innoToggleEdit_Tab0" + i,
            {
                "label": cap_Ribbon_TogglePreview,
                "title": cap_Ribbon_TogglePreview_Title,
                "class": "big innoToggleEdit_Edit",
                "onclick": $.fn.RibbonEditionTypeWritingToggleEditModeClick
            }
        );
        ed.addButton
        (
            "innoSave_Tab0" + i,
            {
                "label": cap_Ribbon_Save,
                "title": cap_Ribbon_Save_Title,
                "class": "big innoSave",
                "onclick": $.fn.RibbonEditionTypeWritingSaveContentClick,
                "value": i
            }
        );
    }
    ed.addButton
    (
        "innoInsertAddGridsterWidget",
        {
            "label": cap_Ribbon_AddGridsterWidget,
            "title": cap_Ribbon_AddGridsterWidget_Title,
            "class": "big innoAddGridsterWidget AddGridsterWidget",
            "onclick": $.fn.RibbonLayoutAddGridsterWidgetClick
        }
    );
    ed.addButton
    (
        "innoInsertLayout01",
        {
            "label": cap_Ribbon_Layout01,
            "title": cap_Ribbon_Layout01_Title,
            "class": "big innoInsertLayout Layout01",
            "onclick": $.fn.RibbonEditionLayoutGetAndInsertLayoutClick,
            "value": "Layout01"
        }
    );
    ed.addButton
    (
        "innoInsertLayout02H",
        {
            "label": cap_Ribbon_Layout02H,
            "title": cap_Ribbon_Layout02H_Title,
            "class": "big innoInsertLayout Layout02H",
            "onclick": $.fn.RibbonEditionLayoutGetAndInsertLayoutClick,
            "value": "Layout02H"

        }
    );
    ed.addButton
    (
        "innoInsertLayout02V",
        {
            "label": cap_Ribbon_Layout02V,
            "title": cap_Ribbon_Layout02V_Title,
            "class": "big innoInsertLayout Layout02V",
            "onclick": $.fn.RibbonEditionLayoutGetAndInsertLayoutClick,
            "value": "Layout02V"
        }
    );
    ed.addButton
    (
        "innoInsertLayout031",
        {
            "label": cap_Ribbon_Layout031,
            "title": cap_Ribbon_Layout031_Title,
            "class": "big innoInsertLayout Layout031",
            "onclick": $.fn.RibbonEditionLayoutGetAndInsertLayoutClick,
            "value": "Layout031"
        }
    );
    ed.addButton
    (
        "innoInsertLayout032",
        {
            "label": cap_Ribbon_Layout032,
            "title": cap_Ribbon_Layout032_Title,
            "class": "big innoInsertLayout Layout032",
            "onclick": $.fn.RibbonEditionLayoutGetAndInsertLayoutClick,
            "value": "Layout032"
        }
    );
    ed.addButton
    (
        "innoInsertLayout041",
        {
            "label": cap_Ribbon_Layout041,
            "title": cap_Ribbon_Layout041_Title,
            "class": "big innoInsertLayout Layout041",
            "onclick": $.fn.RibbonEditionLayoutGetAndInsertLayoutClick,
            "value": "Layout041"
        }
    );
    ed.addButton
    (
        "innoInsertLayout042",
        {
            "label": cap_Ribbon_Layout042,
            "title": cap_Ribbon_Layout042_Title,
            "class": "big innoInsertLayout Layout042",
            "onclick": $.fn.RibbonEditionLayoutGetAndInsertLayoutClick,
            "value": "Layout042"
        }
    );
    ed.addButton
    (
        "innoSourceHTML",
        {
            "label": cap_Ribbon_SourceHTML,
            "title": cap_Ribbon_SourceHTML_Title,
            "class": "big innoSourceHTML SourceHTML",
            "onclick": $.fn.RibbonCodeMirrorHTMLSourceClick
        }
    );
    ed.addButton
    (
        "innoSourceCSS",
        {
            "label": cap_Ribbon_SourceCSS,
            "title": cap_Ribbon_SourceCSS_Title,
            "class": "big innoSourceCSS SourceCSS",
            "onclick": $.fn.RibbonCodeMirrorCSSSourceClick
        }
    );
    ed.addButton
    (
        "innoGeneralSettings",
        {
            "label": cap_Ribbon_GeneralSettings,
            "title": cap_Ribbon_GeneralSettings_Title,
            "class": "big innoGeneralSettings GeneralSettings",
            "onclick": $.fn.RibbonSettingsGeneralClick
        }
    );
    ed.addButton
    (
        "innoPlugIns",
        {
            "label": cap_Ribbon_PlugIns,
            "title": cap_Ribbon_PlugIns_Title,
            "class": "big innoPlugIns PlugIns",
            "onclick": $.fn.RibbonSettingsPlugInsClick
        }
    );
    ed.addButton
    (
        "innoSiteLayout",
        {
            "label": cap_Ribbon_SiteLayout,
            "title": cap_Ribbon_SiteLayout_Title,
            "class": "big innoSiteLayout SiteLayout",
            "onclick": $.fn.RibbonSettingsSiteLayoutClick
        }
    );
    ed.addButton
    (
        "innoRoles",
        {
            "label": cap_Ribbon_Roles,
            "title": cap_Ribbon_Roles_Title,
            "class": "big innoRoles Roles",
            "onclick": $.fn.RibbonSettingsAdminRolesClick
        }
    );
    ed.addButton
    (
        "innoUsers",
        {
            "label": cap_Ribbon_Users,
            "title": cap_Ribbon_Users_Title,
            "class": "big innoUsers Users",
            "onclick": $.fn.RibbonSettingsUsersClick
        }
    );
    ed.addButton
    (
        "innoFilesManagement",
        {
            "label": cap_Ribbon_FileManagement,
            "title": cap_Ribbon_FileManagement_Title,
            "class": "big innoFileManagement FileManagement",
            "onclick": $.fn.RibbonSettingsFileManagmentClick
        }
    );
}

$.fn.TinyMCEInstanceInitialized = function () {
    /// <summary>
    /// Occurs when tiny mce is initialized
    /// Ribbon Sliders
    /// </summary>
    $(".ribbon_tab_btn li").on("click", $.fn.RibbonTabClick);
    var layoutToolBar = $("#divMceRibbonBarPlaceholder").find("div[rel=Layout]");
    var spacingSlidersDiv = $(layoutToolBar.find("div.ribbon_group")[4]);
    spacingSlidersDiv.addClass("spacingRibbonPanel");
    spacingSlidersDiv.html("");
    spacingSlidersDiv.append("<ul><li><label>Margin</label><span id='SliderMargin'></span></li><li><label>Padding</label><span id='SliderPadding'></span></li></ul>");
    spacingSlidersDiv.find("li").each(function () { $(this).find("span").slider({ slide: $.fn.TinyMCERefreshContentSpacing }); });
    $("#divFooEditor_resize").hide();
    $("#divFooEditor_parent").css("display", "block");

    //fix the iframe mode
    var ifr = $("#" + tinyMCEElements + "_ifr");
    //ifr.css("margin-left", "-1px");
    //ifr.css("margin-right", "-1px");
    //ifr.css("padding-top", "14px");

    //$("body", d).css("padding-top", layoutVar_divBodyPaddingTop + "px");
    //$("body", d).css("padding-left", layoutVar_divBodyPaddingLeft + "px");
    //$("body", d).css("padding-right", layoutVar_divBodyPaddingRight + "px");
    //$("body", d).css("padding-bottom", layoutVar_divBodyPaddingBottom + "px");
    //$.fn.TinyMCEResizeActiveEditor($("#MyPrettyCMSContent"));
    var d = ifr[0].contentWindow.document;
    var htmlBribe = '';
    //Content layout transfert

    //htmlBribe = '<link href="/Content/ClientComponents/gridster/jquery.gridster.css" rel="stylesheet" type="text/css" />';
    //$("head", d).append(htmlBribe);
    //htmlBribe = '<link href="/Content/ClientComponents/gridster/jquery.gridster.innovacall.css" rel="stylesheet" type="text/css" />';
    //$("head", d).append(htmlBribe);
    //$.fn.EditionTypeWritingUpdateEditorCSSExtension($("#hidCSSExtension").val());

    //$.fn.ContentLayoutPrepareCSSExtension();
    //$.fn.EditionTypeWritingUpdateContentCSSExtension($("#hidCSSExtension").val());
    $("#divFooEditor_tbl").addClass("notDisplayed");
}

$.fn.TinyMCERefreshContentSpacing = function () {
    /// <summary>
    /// Occurs when user change content lines spacing
    /// ToDo LJO : improve it to store settings in CSS file
    /// REMOVED
    /// </summary>
    var ifr = $("#divFooEditor_ifr");
    var d = ifr[0].contentWindow.document;
    switch ($(this).attr("id")) {
        case "SliderMargin":
            $(".mceEditable", d).css("margin", $(this).slider("value") + "px");
            break;
        case "SliderPadding":
            $(".mceEditable", d).css("padding", $(this).slider("value") + "px");
            break;
    }
}

$.fn.TinyMCEGetContentHack = function () {
    var toReturn = "";
    var ifr = $("#divFooEditor_ifr");
    var d = ifr[0].contentWindow.document;
    toReturn = $("body", d).html();
    return toReturn;
}

$.fn.TinyMCESetContentHack = function (content) {
    var toReturn = "";
    var ifr = $("#divFooEditor_ifr");
    var d = ifr[0].contentWindow.document;
    toReturn = $("body", d).html(content);
    return toReturn;
}

$.fn.TinyMCEMoveInstanceToDiv = function (evt, ui) {
    /// <summary>
    /// Recreate TinyMCE instance on the good div
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    switch (UseMode.getCurrent()) {
        case enUseModes.structureEditMode:
        case enUseModes.contentCodeMode:
        case enUseModes.contentLayoutMode:
        case enUseModes.settingsMode:
        case enUseModes.siteLayoutMode:
            //Content edit not allowed
            break;
        default:
            var clickTargetId = $(this).attr("id")
            $.fn.TinyMCEShow(true, clickTargetId);
            break;
    }
}

//#endregion

//#region Ribbon stuff

$.fn.RibbonEditionTypeWritingToggleEditModeClick = function (evt) {
    /// <summary>
    /// Change Edit mode to structure mode
    /// </summary>
    /// <param name="evt"></param>
    var currentUseMode = UseMode.getCurrent();
    if (currentUseMode != enUseModes.structureEditMode) {
        $.fn.TinyMCEShow(false);
        $(".AdminModeMenuButtonRight,.AdminModeMenuButtonLeft").css("display", "");
        $(".innoToggleEdit_Edit").addClass("innoToggleEdit_Preview");
        $(".innoToggleEdit_Edit").removeClass("innoToggleEdit_Edit");
        $(".LastMenuBarItem").parent().show();
        UseMode.setCurrent(enUseModes.structureEditMode);
    } else {
        $(".AdminModeMenuButtonRight,.AdminModeMenuButtonLeft").css("display", "none");
        $(".innoToggleEdit_Preview").addClass("innoToggleEdit_Edit");
        $(".innoToggleEdit_Preview").removeClass("innoToggleEdit_Preview");
        $(".LastMenuBarItem").parent().hide();
        $("#divBody").addClass("editMode");
        UseMode.setCurrent(enUseModes.contentEditMode);
    }
    if (evt != null) {
        $.fn.EnsureStopPropagation(evt);
    }
}

$.fn.RibbonEditionLayoutGetAndInsertLayoutClick = function (evt) {
    /// <summary>
    /// Load pre build layout
    /// </summary>
    /// <param name="evt"></param>
    var buttonId = $(arguments[0].srcElement || arguments[0].target).parent().attr("id");
    var pos = buttonId.indexOf("_innoInsert");
    layoutCommand = buttonId.substring(pos + 11);
    if ($.fn.EditionIsThereSomeContent()) {
        $.fn.jqDialogConfirm(cap_ConfirmLayoutSlotNotEmptyContentLostIf_Title, cap_ConfirmLayoutSlotNotEmptyContentLostIf_Message, cap_YesButtonCaption, cap_NoButtonCaption, $.fn.ContentLayoutGetPreBuildContentLayout, 450, 150);
    } else {
        $.fn.ContentLayoutGetPreBuildContentLayout(evt);
    }
}

$.fn.RibbonEditionLayoutRemoveLayoutClick = function (evt) {
    /// <summary>
    /// Obsolete
    /// </summary>
    /// <param name="evt"></param>
    var edTmp = $.fn.jqDialogPrepareAndGet('edTmp', null);
    $("#edTmp").html($.fn.TinyMCEGetContentHack());
    $("#edTmp").find(".MyPrettyCMSContentLayout").each(function () {
        $(this).replaceWith(
        function () {
            return "<div>" + $(this).html() + "</div>";
        })
    });
    tinymce.activeEditor.setContent(edTmp.html());
}

$.fn.RibbonLayoutAddGridsterWidgetClick = function () {
    /// <summary>
    /// Add a new Content layout slot
    /// </summary>
    var htmlBribe = '<li data-row="1" data-col="1" data-sizex="2" data-sizey="2" class="mceNonEditable gridsterLi MyPrettyCMSSlot">' + gridsterLayoutSlotDropHtml + '<div class="mceEditable"></div></li>';
    gridster.add_widget(htmlBribe);
}

$.fn.RibbonEditionTypeWritingSaveContentClick = function (evt) {
    /// <summary>
    /// Save content ribbon button click handle
    /// </summary>
    /// <param name="evt"></param>
    var currentUseMode = UseMode.getCurrent();
    switch (currentUseMode) {
        case enUseModes.structureEditMode:
            break;
        case enUseModes.contentEditMode:
            $.fn.jqDialogFunction("divStructurePage", StructurePageEditorTitle, $.fn.EditionTypeWritingSaveContent, null, null, 800, 450, null, true);
            break;
        case enUseModes.contentCodeMode:
            //Check if contentCode modified
            break;
        case enUseModes.contentLayoutMode:
            //Check if contentLayout modified
            break;
        case enUseModes.settingsMode:
            //Check if settings modified
            break;
        case enUseModes.siteLayoutMode:
            //Check if site layout modified
            break;
    }
}

$.fn.RibbonSettingsGeneralClick = function (evt) {
    /// <summary>
    /// Ribbon button click handler : Settings tab General Settings
    /// </summary>
    /// <param name="evt"></param>
    $.fn.jqDialogFunction("AdminSettingsDialogDiv", cap_Settings_AdminSettingsDialog_EditFormTitle, $.fn.AdminSettingsDialogOkClick, null, $.fn.AdminSettingsDialogFeed, 650, 620, null, false, true);
}

$.fn.RibbonSettingsPlugInsClick = function (evt) {
    /// <summary>
    /// Ribbon button click handler : Plug ins
    /// </summary>
    /// <param name="evt"></param>
    $.fn.jqDialogAlert("Plug ins", "Coming soon !");
}

$.fn.RibbonSettingsSiteLayoutClick = function (evt) {
    /// <summary>
    /// Ribbon button click handler : Site layout
    /// </summary>
    /// <param name="evt"></param>
    if (UseMode.getCurrent() != enUseModes.siteLayoutMode) {
        UseMode.setCurrent(enUseModes.siteLayoutMode);
    } else {
        UseMode.setCurrent(enUseModes.settingsMode);
    }
}

$.fn.RibbonSettingsAdminRolesClick = function (evt) {
    /// <summary>
    /// Ribbon button click handler : AdminRoles
    /// </summary>
    /// <param name="evt"></param>
    evt.preventDefault();
    $.fn.SettingsAdminRolesDialog();
}

$.fn.RibbonSettingsUsersClick = function (evt) {
    /// <summary>
    /// Ribbon button click handler : AdminUsers
    /// </summary>
    /// <param name="evt"></param>
    evt.preventDefault();
    $.fn.SettingsUsersDialog();
    $.fn.EnsureStopPropagation(evt);
    return false;
}

$.fn.RibbonSettingsFileManagmentClick = function (evt) {
    /// <summary>
    /// Open the files manager
    /// </summary>
    /// <param name="evt"></param>
    var fileBrowserURL = "/" + uiLanguage + "/finder";
    $.fn.jqDialogContainer("divFinder", "File management", $.fn.prepareFileManagementIFrame, null, 980, 690, "<iframe src='" + fileBrowserURL + "' frameborder='0' class='fileManagementIFrame' scrolling='no'></iframe>");
}

$.fn.RibbonTabClick = function (evt, ui) {
    /// <summary>
    /// Ribbon events handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    currentTabIndex = $(this).index();
    var currentUseMode = UseMode.getCurrent();
    switch (currentTabIndex) {
        case enRibbonTabs._00Start:
            switch (currentUseMode) {
                case enUseModes.structureEditMode:
                    //The UseMode is already structureEditMode
                    break;
                default:
                    UseMode.setCurrent(enUseModes.contentEditMode);
                    break;
            }
            break;
        case enRibbonTabs._01Insert:
        case enRibbonTabs._04Image:
        case enRibbonTabs._05Table:
            UseMode.setCurrent(enUseModes.contentEditMode);
            break;
        case enRibbonTabs._02Layout:
            UseMode.setCurrent(enUseModes.contentLayoutMode);
            break;
        case enRibbonTabs._03Code:
            UseMode.setCurrent(enUseModes.contentCodeMode);
            break;
        case enRibbonTabs._06Settings:
            UseMode.setCurrent(enUseModes.settingsMode);
            break;
    }
}


//#endregion

/*#region CodeMirror*/

$.fn.CodeMirrorChange = function (cm, changeObj) {
    ///<summary>
    ///Code mirror OnChange event handler
    ///</summary>
    /// <param name="cm">Code mirror editor</param>
    /// <param name="changeObj">??</param>
    cmChanged = cmInitialContent != cm.getValue();
    var parentItem;
    switch (cmWhat) {
        case "js":
            //NotImplementedYet
            break;
        case "css":
            parentItem = $("#divFooEditor_innoSourceCSS");
            break;
        case "html":
            parentItem = $("#divFooEditor_innoSourceHTML");
            break;
    }
    var divCodeSave = parentItem.find("#divCodeSaveContainer");
    if (cmChanged) {
        $.fn.CodeMirrorSaveCancelPanelBuild(parentItem);
    } else {
        $.fn.CodeMirrorSaveCancelPanelRemove();
    }
}

$.fn.CodeMirrorCancelSaveCode = function (evt, ui) {
    /// <summary>
    /// Cancel save CodeMirror modifications click handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    cmChanged = false;
    $.fn.CodeMirrorSaveCancelPanelRemove();
}


/*#endregion*/

//#region Edition stuff

$.fn.EditionTypeWritingUpdateContentCSSExtension = function (CSSExtension) {
    /// <summary>
    /// Transfert CSS Extension to document head (not in the editor)
    /// </summary>
    /// <param name="CSSExtension">Style bloc html</param>
    var htmlBribe = CSSExtension.replace("/*SlotsBorders*/", "li.gridsterLi {border:1px red dashed} .mceEditable { border:1px green dashed; width:100%; }\n");
    if ($("#CSSExtension").length > 0) {
        $("#CSSExtension").remove();
    }
    var cssExtension = "<style id=\"CSSExtension\" type=\"text/css\">";
    cssExtension += htmlBribe;
    cssExtension += "</style>";
    $("head").append(cssExtension);
}

$.fn.EditionBindLayoutSlotsClick = function () {
    /// <summary>
    /// Bind all layout slots to click handler
    /// </summary>
    $("#divContent .layoutSlot").each(function () {
        $(this).on("click", $.fn.TinyMCEMoveInstanceToDiv);
    });
}

$.fn.EditionIsThereSomeContent = function () {
    /// <summary>
    /// Return true if editable contents contains something
    /// </summary>
    /// <returns type="int"></returns>
    var tmp = "";
    if ($("div.layoutSlot").length > 0) {
        $("div.layoutSlot").each(function () {
            tmp += $(this).html();
        });
    }
    return tmp.length;
}

$.fn.EditionTypeWritingEditorContentResize = function (evt, ui) {
    /// <summary>
    /// Not used yet
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    alert("yes !");
}

$.fn.EditionTypeWritingSaveContent = function () {
    /// <summary>
    /// Save the content of the page 
    /// ICI
    /// </summary>
    var content = "";
    $(this).dialog("close");
    $.fn.TinyMCEShow(false);
    content = $("#divContent").html();
    $("#hidNewContent").val(content);
    var v = $("#StructurePage_FK_LayoutMenu_Translation").val();
    var form = $("#frmManagedContent");
    $("#divStructurePage").parent().appendTo(form);
    var url = "/" + $("#hidControllerName").val() + "/Save/" + v;
    form.attr("action", url);
    form.submit();
}

//#endregion

//#region ContentLayout Stuff

$.fn.ContentLayoutGetPreBuildContentLayout = function (evt) {
    /// <summary>
    /// Prépare pre built layout
    /// </summary>
    /// <param name="layoutId"></param>
    /// <returns type=""></returns>
    if ($(this).attr("id") == "dialogMessage") {
        $(this).dialog("close");
    }
    var layoutId = layoutCommand;
    var htmlBribe = '';
    var gridWidth = 0;
    var availableWidth = $("#divContent").width();
    var availableHeight = sp_ContentHeight;
    var maxiW = Math.round((availableWidth + gridsterWidget_base_width) / gridsterWidget_base_width);
    var maxiH = Math.round((availableHeight + gridsterWidget_base_height) / gridsterWidget_base_height);
    var sizex;
    var sizey;
    var sizex1;
    var sizey1;
    var sizex2;
    var sizey2;
    var sizex3;
    var sizey3;
    var newsizex;
    var newsizey;
    var tmp;

    //if ($("#divContent").height() < sp_ContentHeight) {
    //    $("#divContent").css("height", sp_ContentHeight + "px");
    //}

    for (var i = 1; i < maxiW; i++) {
        newsizex = Math.round((i * gridsterWidget_base_width) +
            ((i - 1) * gridsterMarginLeft * 2));
        if (newsizex > availableWidth) break;
        sizex = i;
    }
    for (var i = 1; i < maxiH; i++) {
        newsizey = (i * gridsterWidget_base_height) +
            ((i - 1) * gridsterMarginTop * 2);
        if (newsizey > availableHeight) break;
        sizey = i;
    }
    switch (layoutId) {
        case "Layout01":
            htmlBribe += '<div class="gridster ">\n';
            htmlBribe += '    <ul class="gridsterUl ">\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-1" class=" gridsterLi MyPrettyCMSSlot" data-row="1" data-col="1" data-sizex="' + sizex + '" data-sizey="' + sizey + '">\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-1LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '    </ul>\n';
            htmlBribe += '</div>\n';
            break;
        case "Layout02H":
            sizey1 = Math.round(sizey / 2);
            sizey2 = sizey - sizey1;
            htmlBribe += '<div class="gridster ">\n';
            htmlBribe += '    <ul class="gridsterUl ">\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-1" data-col="1" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex + '" data-sizey="' + sizey1 + '">\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-1LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-2" data-col="1" data-row="' + (sizey1 + 1) + '" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex + '" data-sizey="' + sizey2 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-2LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '    </ul>\n';
            htmlBribe += '</div>\n';
            break;
        case "Layout02V":
            tmp = sizex / 2;
            rTmp = Math.round(tmp);
            if (tmp == rTmp) {
                sizex1 = rTmp;
                sizex2 = rTmp;
            } else {
                sizex1 = rTmp;
                sizex2 = rTmp - 1;
            }
            sizex = Math.round(sizex / 2) - 1;
            htmlBribe += '<div class="gridster ">\n';
            htmlBribe += '    <ul class="gridsterUl ">\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-1" data-col="1" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex1 + '" data-sizey="' + sizey + '">\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-1LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-2" data-col="' + (sizex + 1) + '" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex2 + '" data-sizey="' + sizey + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-2LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '    </ul>\n';
            htmlBribe += '</div>\n';
            break;
        case "Layout031":
            tmp = sizex / 2;
            rTmp = Math.round(tmp);
            if (tmp == rTmp) {
                sizex1 = rTmp;
                sizex2 = rTmp;
            } else {
                sizex1 = rTmp;
                sizex2 = rTmp - 1;
            }
            sizey1 = Math.round(sizey / 2);
            sizey2 = sizey - sizey1;
            htmlBribe += '<div class="gridster ">\n';
            htmlBribe += '    <ul class="gridsterUl ">\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-1" data-col="1" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex + '" data-sizey="' + sizey1 + '">\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-1LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-2" data-col="1" data-row="2" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex1 + '" data-sizey="' + sizey2 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-2LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-3" data-col="2" data-row="' + (sizey1 + 1) + '" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex2 + '" data-sizey="' + sizey2 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-3LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '    </ul>\n';
            htmlBribe += '</div>\n';
            break;
        case "Layout032":
            tmp = sizex / 2;
            rTmp = Math.round(tmp);
            if (tmp == rTmp) {
                sizex1 = rTmp;
                sizex2 = rTmp;
            } else {
                sizex1 = rTmp;
                sizex2 = rTmp - 1;
            }
            sizey1 = Math.round(sizey / 2);
            sizey2 = sizey - sizey1;
            htmlBribe += '<div class="gridster ">\n';
            htmlBribe += '    <ul class="gridsterUl ">\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-1" data-col="1" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex1 + '" data-sizey="' + sizey1 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-1LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-2" data-col="' + (sizex1 + 1) + '" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex2 + '" data-sizey="' + sizey1 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-2LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-3" data-col="1" data-row="' + (sizey1 + 1) + '" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex + '" data-sizey="' + sizey2 + '">\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-3LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '    </ul>\n';
            htmlBribe += '</div>\n';
            break;
        case "Layout041":
            tmp = sizex / 2;
            rTmp = Math.round(tmp);
            if (tmp == rTmp) {
                sizex1 = rTmp;
                sizex2 = rTmp;
            } else {
                sizex1 = rTmp;
                sizex2 = rTmp - 1;
            }
            sizey1 = Math.round(sizey / 2);
            sizey2 = sizey - sizey1;
            htmlBribe += '<div class="gridster ">\n';
            htmlBribe += '    <ul class="gridsterUl ">\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-1" data-col="1" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex1 + '" data-sizey="' + sizey1 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-1LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-2" data-col="2" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex2 + '" data-sizey="' + sizey1 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-2LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-3" data-col="1" data-row="' + (sizey1 + 1) + '" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex1 + '" data-sizey="' + sizey2 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-3LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-4" data-col="2" data-row="' + (sizey1 + 1) + '" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex2 + '" data-sizey="' + sizey2 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-4LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '    </ul>\n';
            htmlBribe += '</div>\n';
            break;
        case "Layout042":
            tmp = sizex / 2;
            rTmp = Math.round(tmp);
            if (tmp == rTmp) {
                sizex1 = rTmp;
                sizex2 = rTmp;
            } else {
                sizex1 = rTmp;
                sizex2 = rTmp - 1;
            }
            tmp = sizey / 3;
            rTmp = Math.round(tmp);
            if (rTmp == tmp) {
                sizey1 = tmp;
                sizey2 = tmp;
                sizey3 = tmp;
            } else {
                sizey1 = rTmp;
                tmp = sizey / 2;
                rTmp = Math.round(tmp);
                if (rTmp == tmp) {
                    sizey2 = tmp;
                    sizey3 = tmp;
                } else {
                    sizey2 = rTmp;
                    sizey3 = sizey - (sizey1 + sizey2);
                    if (sizey3 < 1) {
                        sizey3 = 1;
                        sizey2 = sizey2 - 1;
                    }
                }
            }

            htmlBribe += '<div class="gridster ">\n';
            htmlBribe += '    <ul class="gridsterUl ">\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-1" data-col="1" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex1 + '" data-sizey="' + sizey + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-1LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-2" data-col="' + (sizex1 + 1) + '" data-row="1" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex2 + '" data-sizey="' + sizey1 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-2LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-3" data-col="' + (sizex1 + 1) + '" data-row="' + (sizey1 + 1) + '" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex2 + '" data-sizey="' + sizey2 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-3LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '        <li id="MyPrettyCMSContentSlot-4" data-col="' + (sizex1 + 1) + '" data-row="' + (sizey1 + sizey2 + 1) + '" class=" gridsterLi MyPrettyCMSSlot" data-sizex="' + sizex2 + '" data-sizey="' + sizey3 + '" >\n';
            htmlBribe += '            <div id="MyPrettyCMSContentSlot-4LayoutSlot" class="mceEditable layoutSlot"></div>\n';
            htmlBribe += '        </li>\n';
            htmlBribe += '    </ul>\n';
            htmlBribe += '</div>\n';
            break;

    }
    $("#divContent").html(htmlBribe);
    $.fn.ContentLayoutActivateGridster(true);
    $("#divContent .layoutSlot").each(function () {
        var editableDivId = "";
        var parent = $(this).parent();
        var parentWidth = parseInt(parent.width());
        var parentHeight = parseInt(parent.height());
        $(this).css("width", parentWidth + "px");
        $(this).css("height", parentHeight + "px");
        //$(this).css("background-color", "green");
    });
    $.fn.EditionBindLayoutSlotsClick();
    $.fn.ContentLayoutPrepareCSSExtension();
}

$.fn.ContentLayoutActivateGridster = function (activateIt) {
    /// <summary>
    /// Activate gridster content layout edition
    /// </summary>
    /// <param name="activateIt">Boolean</param>

    var uniqueIds = new Array();
    var CSSExtensions = $("head").find("#CSSExtension").each(function () {
        $(this).uniqueId();
        uniqueIds.push($(this).attr("id"));
    });
    for (var i = 0; i < uniqueIds.length; i++) {
        var currentSelector = "#" + uniqueIds[i];
        $("head").find(currentSelector);
        if ($(currentSelector).length > 0) {
            $(currentSelector).remove();
        };
    }
    gridster = $(".gridster ul").gridster({
        widget_base_dimensions: [gridsterWidget_base_width, gridsterWidget_base_height],
        widget_margins: [gridsterMarginLeft, gridsterMarginTop],
        helper: 'clone',
        resize: {
            enabled: true
        }
    }).data('gridster');
    $("#divContent .gs-w").each(function () {
        $(this).prepend(gridsterLayoutSlotDropHtml);
        $(this).find(".layoutSlotDrop").on("click", $.fn.ContentLayoutDropSlotConfirmRequest);
    });
}

$.fn.ContentLayoutDropSlot = function () {
    /// <summary>
    /// drop a lyout slot
    /// </summary>
    $("#dialogMessage").dialog("close");
    gridster.remove_widget(gridsterLayoutSlotToDrop);
}

$.fn.ContentLayoutDropSlotConfirmRequest = function (evt, ui) {
    /// <summary>
    /// 
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    gridsterLayoutSlotToDrop = $(this).parent();
    if ($(this).parent().parent().find(".gridsterLi").length > 1) {
        if ($(this).parent().find(".mceEditable").html() != "") {
            $.fn.jqDialogConfirm(cap_ConfirmDropNonEmptyLayoutSlot_Title, cap_ConfirmDropNonEmptyLayoutSlot_Message, cap_YesButtonCaption, cap_NoButtonCaption, $.fn.ContentLayoutDropSlot, 80, 450);
        } else {
            $.fn.ContentLayoutDropSlot();
        }
    } else {
        $.fn.jqDialogAlert(cap_Warning, cap_LayoutSlotCannotBeRemoved_Message, null);
    }
}

$.fn.ContentLayoutPrepareCSSExtension = function () {
    /// <summary>
    /// OBSOLETE : These rules are used to position the content blocks in run mode and the highlight in design mode 
    /// </summary>
    gridsterEditorCSSExtension = "#divContent ul.gridsterUl li.gridsterLi {\n";
    gridsterEditorCSSExtension += "\t" + "position:absolute;\n";
    gridsterEditorCSSExtension += "}\n";
    var blockCounter = 1;
    console.log(".gridsterUl width : " + $(".gridsterUl").width() + "px");
    $("#divContent .gs-w").each(function () {
        var li = $(this);
        li.attr("id", "MyPrettyCMSContentSlot-" + blockCounter);
        li.attr("style", "");
        sp_ContentRealHeight = $(".gridsterUl").css("height").replace("px", "").trim();
        $("#divContent").css("height", sp_ContentRealHeight + "px");
        //Gridster UL Width
        var liWidth = Math.round(li.width());
        var liHeight = Math.round(li.height());
        var liOffset = li.offset();
        var liParentOffset = li.parent().offset();
        //ToDo LJO Coriger top/left
        var liTop = liParentOffset.top - liOffset.top;
        var liLeft = liParentOffset.left - liOffset.left;
        var currentSelector = "#MyPrettyCMSContentSlot-" + blockCounter;
        gridsterEditorCSSExtension += currentSelector + ".MyPrettyCMSSlot {\n";
        gridsterEditorCSSExtension += "\t" + "top:" + liTop + "px;\n";
        gridsterEditorCSSExtension += "\t" + "left:" + liLeft + "px;\n";
        gridsterEditorCSSExtension += "\t" + "width:" + liWidth + "px;\n";
        gridsterEditorCSSExtension += "\t" + "min-height:" + liHeight + "px;\n";
        gridsterEditorCSSExtension += "\t" + "margin-left:" + gridsterMarginLeft + "px;\n";
        gridsterEditorCSSExtension += "\t" + "margin-top:" + gridsterMarginTop + "px;\n";
        gridsterEditorCSSExtension += "\n}\n";
        gridsterEditorCSSExtension += currentSelector + ".MyPrettyCMSSlot div.mceEditable {\n";
        gridsterEditorCSSExtension += "\t" + "float:left;\n";
        gridsterEditorCSSExtension += "\n}\n";
        li.attr("style", "");
        blockCounter++;
        $("#hidCSSExtension").val(gridsterEditorCSSExtension);
    });
}



//#endregion

//#region show hide tools (Layout handles, Editor, gridster) 

$.fn.TinyMCEShow = function (showIt, elementId) {
    /// <summary>
    /// Show or hide editor for a div
    /// </summary>
    /// <param name="show" type="boolean">True shows, False hides</param>
    /// <param name="elementId" optionnal>div id</param>

    var content = "";
    var lastLayoutSlot;

    if (elementId == undefined || elementId == "") {
        if (lastLayoutSlotId != "") {
            elementId = lastLayoutSlotId;
        } else {
            var layoutSlots = $(".layoutSlot");
            if (layoutSlots.length > 0) {
                elementId = layoutSlots[0].id;
            } else {
                showIt = false;
            }
        }
    }

    $.fn.TinyMCEContentTransfertToSlot();

    if (showIt) {
        var slotToEdit = $("#" + elementId);
        if (tinymce.editors.length == 0) {
            //TODO verifier mais ne doit plus arriver...
            tinyMCEElements = elementId;
            $.fn.TinyMCECreateTinyMCEInstance();
        }
        lastLayoutSlotId = elementId;
        lastLayoutSlot = $("#" + lastLayoutSlotId);
        if (lastLayoutSlot.length > 0) {
            if (tinymce.editors.length > 0) {
                tinymce.editors[0].setContent(lastLayoutSlot.html());
            }
        }

        var ed = tinyMCE.editors[0];
        var edContainer = $("#divFooEditor_parent");
        var edTable = $("#divFooEditor_tbl");
        var edIFrame = $("#" + ed.editorId + "_ifr");
        var slotWidth = slotToEdit.width();
        var slotHeight = slotToEdit.height();
        var mceStatusBarPosYFix = 0;
        var mceStatusBarPosXFix = 0;
        var edContainerOffset = slotToEdit.offset();
        var edContainerLeft = edContainerOffset.left;
        var edContainerTop = edContainerOffset.top;
        edContainer.css("position", "absolute");
        edContainer.css("z-index", slotToEdit.zIndex() + 1);
        edContainer.css("float", "left");
        edContainer.css("left", parseInt((edContainerLeft) + "px"));
        edContainer.css("top", parseInt((edContainerTop) + "px"));
        edContainer.css("width", (slotWidth + 4) + "px");

        edTable.removeClass("notDisplayed");

        edTable.css("width", (slotWidth + mceStatusBarPosXFix) + "px");

        edIFrame.css("width", (slotWidth + mceStatusBarPosXFix) + "px");

        edContainer.css("height", (slotHeight - mceStatusBarPosYFix + 14) + "px");
        edTable.css("height", (slotHeight + mceStatusBarPosYFix) + "px");
        edIFrame.css("height", (slotHeight + mceStatusBarPosYFix) + "px");
        edContainer.css("display", "block");
        $.fn.TinyMCEAddLayoutStyle();
        tinyMCELastElements = elementId;
        $("#divFooEditor_resize").css("display", "none");
        ed.focus();
        $(".mceEditor").css("background-color", slotToEdit.css("background-color"));
        //slotToEdit.css("display","none")
    } else {
        if (tinymce.editors.length > 0) {
            tinyMCE.DOM.hide();
            $("#divFooEditor_parent").css("display", "none");
        }
        tinyMCEElements = 'divFooEditor';
        //Verify if toolbar created
        var tr = $("#divMceRibbonBarPlaceholder").find(".mceLayout").find("tr");
        if (tr.length == 0) {
            $.fn.TinyMCECreateTinyMCEInstance();
        }
        //$(".layoutSlot").css("display", "block");
    }
}

$.fn.TinyMCEContentTransfertToSlot = function () {
    /// <summary>
    /// Replace lastLayoutSlot content with tiny mce content.
    /// </summary>
    if (lastLayoutSlotId != "") {
        if (tinymce.editors.length > 0) {
            content = tinymce.editors[0].getContent();
            $("#" + lastLayoutSlotId).html(content);
        }
    }
}

$.fn.ContentLayoutGridsterShow = function (showIt) {
    /// <summary>
    /// If show it, create gridster instance if necessary and activate it.
    /// </summary>
    /// <param name="showIt"></param>
    if (showIt) {
        if (gridster == undefined) {
            var uniqueIds = new Array();
            var CSSExtensions = $("head").find("#CSSExtension").each(function () {
                $(this).uniqueId();
                uniqueIds.push($(this).attr("id"));
            });
            for (var i = 0; i < uniqueIds.length; i++) {
                var currentSelector = "#" + uniqueIds[i];
                $("head").find(currentSelector);
                if ($(currentSelector).length > 0) {
                    $(currentSelector).remove();
                };
            }
            gridster = $(".gridster ul").gridster({
                widget_base_dimensions: [gridsterWidget_base_width, gridsterWidget_base_height],
                widget_margins: [gridsterMarginLeft, gridsterMarginTop],
                helper: 'clone',
                resize: {
                    enabled: true
                }
            }).data('gridster');
            $("#divContent .gs-w").each(function () {
                $(this).prepend(gridsterLayoutSlotDropHtml);
                $(this).find(".layoutSlotDrop").on("click", $.fn.ContentLayoutDropSlotConfirmRequest);
            });
        }
        gridster.enable();
        gridster.enable_resize();
        $(".layoutSlotDrop").show();
        $(".layoutSlot").addClass("layoutMode");
    } else {
        if (gridster != undefined) {
            gridster.disable();
            gridster.disable_resize();
            $(".layoutSlotDrop").hide();
            $(".layoutSlot").removeClass("layoutMode");
        }
    }
}

$.fn.SettingsSiteLayoutHandlesShow = function (showIt) {
    /// <summary>
    /// Displays or hide Layout handles (must be transfered to partial layout)
    /// </summary>
    /// <param name="displayHandles">bool</param>
    if (!showIt) {
        $(".layoutHandle").remove();
        $(".LayoutBalloon").remove();
        $(".LayoutUploadButtons").remove();
        $(".resizableBlockContainer").unbind("click");
        if ($("#AdminSettingsLayoutShowHideDialogDiv").length > 0) {
            $("#AdminSettingsLayoutShowHideDialogDiv").dialog("close");
            $("#AdminSettingsLayoutShowHideDialogDiv").parent().remove();
        }
    } else {
        if ($("#AdminSettingsLayoutShowHideDialogDiv").length == 0) {
            $.fn.BuildDisplayBlockDialog(); // In the JS of the layout 
            $("#AdminSettingsLayoutShowHideDialogDiv ul li").append("<div class='AdminSettingsLayoutCSSDetails ui-icon ui-icon-gear' title='" + cap_AdminSettingsLayoutCSSDetails_Help + "'></div>");
            $("#AdminSettingsLayoutShowHideDialogDiv ul li .AdminSettingsLayoutCSSDetails").on("click", $.fn.AdminSettingsLayoutBlockCustomizationClick)
            $("#heightModeSelectorDiv input[type=radio]").on("change", $.fn.AdminSettingsLayoutHeightModeSelectorChange);
            $.fn.AdminSettingsLayoutDisplayBlockModeBlocColorPickerBuild("#AdminSettingsLayoutShowHideDialogDiv ul li");

            $.fn.AdminSettingsLayoutRefreshDisplayBoxesToolboxDialog();
            $.fn.AdminSettingsLayoutRefreshDisplayBoxesBindCheckboxes();
        } else {
            $("#AdminSettingsLayoutShowHideDialogDiv").show();
        }
        $("#AdminSettingsLayoutShowHideDialogDiv").dialog(
        {
            title: cap_AdminSettingsLayoutShowHideDialog,
            resizable: false,
            position: { my: "left top", at: "left+10 bottom+50", of: "#divMceRibbonBarPlaceholder" },
            width: "220px"
        }
        );
        htmlBribe = "";
        //var htmlBribe = "<div class=\"BGImageUploadButton\"></div>"
        //$(".BGUpload").append(htmlBribe);
        //$(".BGImageUploadButton").on("click", $.fn.AdminSettingsLayoutUploadBG);
        //$(".BGImageUploadButton").mouseenter($.fn.AdminSettingsLayoutUploadBGMouseEnter);
        //$(".BGImageUploadButton").mouseleave($.fn.AdminSettingsLayoutUploadBGMouseOut);
        $(".resizableBlockContainer").on("click", $.fn.AdminSettingsLayoutResizableZoneClick);
    }
}

//#endregion

//#region Admin settings stuff

$.fn.AdminSettingsAdminUserOkClick = function (evt, ui) {
    /// <summary>
    /// Admin user ok click handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var form = $(this).parent().find("form");
    form.find("#DialogToClose").val("#AdminDivDialogUsersEdit");
    form.attr("action", "/Admin/ContactUserSave/" + uiLanguage);
    form.find("#User_CreationDate").addClass("ignore");
    form.find("#User_LastModified").addClass("ignore");
    form.find("#User_LastLoginDate").addClass("ignore");
    form.find("#User_LastActivityDate").addClass("ignore");
    form.find("#User_LastLockedOutDate").addClass("ignore");
    form.find("#User_LastPasswordChangedDate").addClass("ignore");
    form.find("Contact_IconPath").val($("#UserProfileIconImg").attr("src"));

    $.validator.unobtrusive.parse(form);
    form.validate();
    if (form.valid()) {
        form.submit();
    }
}

$.fn.AdminSettingsDialogBuild = function (a, b, c) {
    /// <summary>
    /// Admin Settings dialog feed request result handler
    /// </summary>
    if (a.success) {
        $(a.domElementToUpdate).html(a.htmlContent);
        var dialogSelector = "#AdminSettingsDialog";
        var dialog = $(dialogSelector);
        var form = dialog.find("#frmAdminSettingsDialog");
        form.attr("action", "/AdminSettings/SettingsSave/" + uiLanguage);
        form.find("#DialogToClose").val(dialogSelector);
        $("#Settings_JQueryCornersRounded").on("click", $.fn.refreshSample);
        $("#Settings_JQueryUITheme").on("click", $.fn.refreshSample);
        $("#Settings_KendoUITheme").on("click", $.fn.refreshSample);
        $("#AdminSettings_Tabs").tabs();
        $.fn.refreshSample();
    } else {
        $.fn.AjaxResponseFailed(a);
    }
}

$.fn.AdminSettingsDialogFeed = function (evt) {
    /// <summary>
    /// Ribbon Settings tab General Settings dialog request content
    /// </summary>
    $("#AdminSettingsDialog").append(waitImage);
    Simple_JSonModel.HtmlElementToUpdate = "#AdminSettingsDialogDiv";
    var ajaxData = JSON.stringify(Simple_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/AdminSettings/AdminSettingsFeed/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.AdminSettingsDialogBuild,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.AdminSettingsDialogOkClick = function (evt, ui) {
    /// <summary>
    /// General Settings ok button click handler
    /// </summary>
    /// <summary>
    var form = $(this).parent().find("form");
    form.find("#DialogToClose").val("#AdminSettingsDialog");
    form.attr("action", "/AdminSettings/AdminSettingsSave/" + uiLanguage);
    $.validator.unobtrusive.parse(form);
    form.validate();
    if (form.valid()) {
        form.submit();
    }
}

$.fn.AdminSettingsLayoutBlockCustomizationClick = function (evt, ui) {
    /// <summary>
    /// Open edit layout block css dialog
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    if ($("#AdminSettingsLayoutBlockCustomizationDialog").length > 0) {
        $("#AdminSettingsLayoutBlockCustomizationDialog").remove();
    }
    var targetBlock = $(this).parent().data("for");
    var allowhtmledit = $(this).parent().data("allowhtmledit");
    var allowcssedit = $(this).parent().data("allowcssedit");
    if (!(allowhtmledit || allowcssedit)) return false;
    var htmlBribe = "";
    htmlBribe += "<div id='AdminSettingsLayoutBlockCustomizationDialog' data-for='" + targetBlock + "' class='notDisplayed'>\n";
    htmlBribe += "    <div id='AdminSettingsLayoutBlockCustomizationTabs'>\n";
    if (allowhtmledit && allowcssedit) {
        htmlBribe += "    <ul>\n";
        htmlBribe += "    <li><a href='#AdminSettingsLayoutBlockHtmlEdition'>HTML</a></li>\n";
        htmlBribe += "    <li><a href='#AdminSettingsLayoutBlockCssEdition'>CSS</a></li>\n";
        htmlBribe += "    </ul>\n";
    }
    if (allowhtmledit) {
        htmlBribe += "        <div id='AdminSettingsLayoutBlockHtmlEdition' style='height:400px'>\n";
        htmlBribe += "        <textarea id='AdminSettingsLayoutBlockHtmlEditionTextArea'></textarea>\n";
        htmlBribe += "        </div>\n";
    }
    if (allowcssedit) {
        htmlBribe += "        <div id='AdminSettingsLayoutBlockCssEdition'  style='height:400px'>\n";
        htmlBribe += "        <textarea id='AdminSettingsLayoutBlockCssEditionTextArea'></textarea>\n";
        htmlBribe += "        </div>\n";
    }
    htmlBribe += "    </div>\n";
    htmlBribe += "</div>\n";
    $("body").append(htmlBribe);
    var html = $(targetBlock).html();
    var cssProps = "background-color,background-image,background-position,background-repeat";
    var strCss = "";
    var tCss = cssProps.split(",");
    for (var i = 0; i < tCss.length; i++) {
        var prop = tCss[i];
        var propValue = $(targetBlock).css(prop);
        var authorityIndex = propValue.indexOf(Authority);
        if (authorityIndex >= 0) {
            propValue = propValue.replace("http://" + Authority, "").split("\"").join("");

        }
        strCss += "\t" + prop + ":" + propValue + ";\n"
    }
    strCss = targetBlock + " {\n" + strCss + "}";
    //tLayoutCodeMirror.push(CodeMirror($("#AdminSettingsLayoutBlockHtmlEdition")[0],
    //{
    //    value: html,
    //    mode: "html",
    //    lineWrapping: true,
    //    lineNumbers: true,
    //    tabMode: "indent"
    //}));
    //tLayoutCodeMirror.push(CodeMirror($("#AdminSettingsLayoutBlockCssEdition")[0],
    //{
    //    value: strCss,
    //    mode: "css",
    //    lineWrapping: true,
    //    lineNumbers: true,
    //    tabMode: "indent"
    //}));
    //var totalLines = 0;
    //var totalChars = 0;
    //for (var i = 0; i < tLayoutCodeMirror; i++) {
    //    totalLines = tLayoutCodeMirror[i].lineCount();
    //    totalChars = tLayoutCodeMirror[i].getValue().length;
    //    tLayoutCodeMirror[i].autoFormatRange({ line: 0, ch: 0 }, { line: totalLines, ch: totalChars });
    //    tLayoutCodeMirror[i].setSize(null, "450px");
    //    tLayoutCodeMirror[i].setCursor(0, 0);
    //    tLayoutCodeMirror[i].refresh();
    //}
    if (allowhtmledit) {
        $("#AdminSettingsLayoutBlockHtmlEditionTextArea").text(html);
    }
    if (allowcssedit) {
        $("#AdminSettingsLayoutBlockCssEditionTextArea").text(strCss);
    }
    if (allowhtmledit && allowcssedit) {
        $("#AdminSettingsLayoutBlockCustomizationTabs").tabs({ activate: $.fn.AdminSettingsLayoutBlockCustomizationTabsTabActivate });
    }
    $("#AdminSettingsLayoutBlockCustomizationDialog").dialog({
        title: "Layout block customization",
        width: 600,
        height: 593
    });
}

$.fn.AdminSettingsLayoutCancelLayoutClick = function (evt, ui) {
    /// <summary>
    /// Site layout cancel save button click handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    $.fn.AdminSettingsLayoutDisplayHandlesAndUploadButtons(false);
    var cancelSaveButton = $("#SiteLayoutCancelSave");
    $(".premenu").width(cancelSaveButton.data("pageWidth"));
    $(".menu").width(cancelSaveButton.data("pageWidth"));
    $(".postmenu").width(cancelSaveButton.data("pageWidth"));
    $("#MyPrettyCMSContent").width(cancelSaveButton.data("pageWidth"));

    $(".premenu").height(cancelSaveButton.data("premenuHeight"));
    $(".postmenu").height(cancelSaveButton.data("postMenuHeight"));
    $("#MyPrettyCMSContent").height(cancelSaveButton.data("bodyHeight"));

    $.fn.TinyMCEResizeActiveEditor($("#divFooEditor"));
    $("#divSiteLayoutSaveContainer").remove();
    $.fn.EnsureStopPropagation(evt);
}

$.fn.AdminSettingsLayoutDisplayBlockModeBlocColorPickerChange = function () {
    $($(this).parent().data("for")).css("background-color", "rgba(" + $(this).val() + ",0.5)");
}

$.fn.AdminSettingsLayoutDisplayHandlesAndUploadButtons = function (displayHandles) {
    /// <summary>
    /// Displays or hide Layout handles (must be transfered to partial layout)
    /// </summary>
    /// <param name="displayHandles">bool</param>
    if (!displayHandles) {
        $(".layoutHandle").remove();
        $(".LayoutBalloon").remove();
        $(".LayoutUploadButtons").remove();
        $(".resizableBlockContainer").unbind("click");
        if ($("#AdminSettingsLayoutShowHideDialogDiv").length > 0) {
            $("#AdminSettingsLayoutShowHideDialogDiv").dialog("close");
            $("#AdminSettingsLayoutShowHideDialogDiv").parent().remove();
        }
    } else {
        if ($("#AdminSettingsLayoutShowHideDialogDiv").length == 0) {
            $.fn.BuildDisplayBlockDialog(); // In the JS of the layout 
            $("#AdminSettingsLayoutShowHideDialogDiv ul li").append("<div class='AdminSettingsLayoutCSSDetails ui-icon ui-icon-gear' title='" + cap_AdminSettingsLayoutCSSDetails_Help + "'></div>");
            $("#AdminSettingsLayoutShowHideDialogDiv ul li .AdminSettingsLayoutCSSDetails").on("click", $.fn.AdminSettingsLayoutBlockCustomizationClick)
            $("#heightModeSelectorDiv input[type=radio]").on("change", $.fn.AdminSettingsLayoutHeightModeSelectorChange);
            $.fn.AdminSettingsLayoutDisplayBlockModeBlocColorPickerBuild("#AdminSettingsLayoutShowHideDialogDiv ul li");

            $.fn.AdminSettingsLayoutRefreshDisplayBoxesToolboxDialog();
            $.fn.AdminSettingsLayoutRefreshDisplayBoxesBindCheckboxes();
        } else {
            $("#AdminSettingsLayoutShowHideDialogDiv").show();
        }
        $("#AdminSettingsLayoutShowHideDialogDiv").dialog(
        {
            title: cap_AdminSettingsLayoutShowHideDialog,
            resizable: false,
            position: { my: "left top", at: "left+10 bottom+50", of: "#divMceRibbonBarPlaceholder" },
            width: "220px"
        }
        );
        htmlBribe = "";
        //var htmlBribe = "<div class=\"BGImageUploadButton\"></div>"
        //$(".BGUpload").append(htmlBribe);
        //$(".BGImageUploadButton").on("click", $.fn.AdminSettingsLayoutUploadBG)
        //$(".BGImageUploadButton").mouseenter($.fn.AdminSettingsLayoutUploadBGMouseEnter)
        //$(".BGImageUploadButton").mouseleave($.fn.AdminSettingsLayoutUploadBGMouseOut)
        $(".resizableBlockContainer").on("click", $.fn.AdminSettingsLayoutResizableZoneClick);
    }
}

$.fn.AdminSettingsLayoutDisplayBlockModeBlocColorPickerBuild = function (parentSelector) {
    /// <summary>
    /// Prepare simple color picker to colorize blocs during layout
    /// </summary>
    /// <param name="parentSelector"></param>
    var htmlBribe = '';
    htmlBribe += '<select name="colorpicker-picker">'
    + ' <option value="' + $($(this).parent().data("for")).css("background-color") + '>' + $($(this).parent().data("for")).css("background-color") + '</option>'
    + ' <option value="#7bd148">Green</option>'
    + ' <option value="#5484ed">Bold blue</option>'
    + ' <option value="#a4bdfc">Blue</option>'
    + ' <option value="#46d6db">Turquoise</option>'
    + ' <option value="#7ae7bf">Light green</option>'
    + ' <option value="#51b749">Bold green</option>'
    + ' <option value="#fbd75b">Yellow</option>'
    + ' <option value="#ffb878">Orange</option>'
    + ' <option value="#ff887c">Red</option>'
    + ' <option value="#dc2127">Bold red</option>'
    + ' <option value="#dbadff">Purple</option>'
    + ' <option value="#e1e1e1">Gray</option>'
    + '</select>'

    $(parentSelector).append(htmlBribe);
    $(parentSelector + " select[name=colorpicker-picker]").simplecolorpicker({ picker: true, theme: 'glyphicons' });
    $(parentSelector + " .simplecolorpicker").css("float", "right");
    $(parentSelector + " select[name=colorpicker-picker]").on("change", $.fn.AdminSettingsLayoutDisplayBlockModeBlocColorPickerChange);
}


$.fn.AdminSettingsLayoutHeightModeSelectorChange = function (evt, ui) {
    /// <summary>
    /// Occurs when user change height mode
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    sp_ContentHeightMode = $(this).val();
}

$.fn.AdminSettingsLayoutRefreshDisplayBoxesBindCheckboxes = function () {
    /// <summary>
    /// Bind layout block display check box to change
    /// </summary>
    $("#AdminSettingsLayoutShowHideDialogDiv ul li input[type=checkbox]").on("change", $.fn.AdminSettingsLayoutShowHideBlockCheckBoxChange);
}

$.fn.AdminSettingsLayoutRefreshDisplayBoxesToolboxDialog = function () {
    /// <summary>
    /// Verify if blocks are visible and update check box
    /// </summary>
    $("#AdminSettingsLayoutShowHideDialogDiv ul li").each(function () {
        $(this).find("input[type=checkbox]").attr("checked", $($(this).data("for")).is(":visible"));
    });
}

$.fn.AdminSettingsLayoutResizableZoneClick = function (evt, ui) {
    /// <summary>
    /// Occurs when a resizable zone is clicked
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var htmlToAppend;
    var htmlBribe;
    $(".LayoutBalloon").remove();
    $("#AdminSettingsShowHideDialog").remove();
    if ($(this).length > 0) {
        if ($(".layoutHandle").length > 0) {
            $(".layoutHandle").remove();
        }
        layoutHandlesCounter = 0;
        $(this).each(function () {
            //H/W balloon
            var balloonToAppend = "<div class='LayoutBalloon un-corner-all'><ul><li>W:<span class='width'>" + $(this).width() + "px</span></li><li>H:<span class='height'>" + $(this).height() + "px</span></li></ul></div>";
            $(this).append(balloonToAppend);
            /*#region topHandle*/
            switch ($(this).data("resize_axis")) {
                case "y":
                case "xy":
                    htmlBribe = "<div class='ui-icon ui-icon-arrowthick-2-n-s layoutHandleTop layoutHandle' style='z-index:" + (7000 + layoutHandlesCounter) + "'></div>";
                    layoutHandlesCounter++;
                    $(this).append(htmlBribe);
                    $(this).find(".layoutHandleTop").each(function () {
                        $(this).uniqueId();
                        var uniqueId = $(this).attr("id");
                        $(this).draggable(
                        {
                            axis: "y",
                            zIndex: 9999,
                            opacity: 0,
                            helper: function (event) {
                                var toReturn = $('<div id="' + uniqueId + 'Clone" class="LayoutHandleClone" data-handle="top" data-y_impact="' + $(this).parent().data("y_impact") + '" data-x_impact="' + $(this).parent().data("x_impact") + '" data-axis="y" style="z-index:' + (7500 + layoutHandlesCounter) + '"></div>');
                                return toReturn
                            },
                            start: $.fn.AdminSettingsLayoutResizeHandleStartDrag,
                            stop: $.fn.AdminSettingsLayoutResizeHandleStopDrag,
                            drag: $.fn.AdminSettingsLayoutResizeHandleDragging
                        }
                        );
                    });
                    break;
            }
            /*#endregion*/
            /*#region leftHandle*/
            switch ($(this).data("resize_axis")) {
                case "x":
                case "xy":
                    htmlBribe = "<div class='ui-icon ui-icon-arrowthick-2-e-w layoutHandleLeft layoutHandle'style=' z-index:" + (7000 + layoutHandlesCounter) + "'></div>"
                    layoutHandlesCounter++;
                    $(this).append(htmlBribe);
                    $(this).find(".layoutHandleLeft").each(function () {
                        $(this).uniqueId();
                        var uniqueId = $(this).attr("id");
                        $(this).draggable(
                        {
                            axis: "x",
                            zIndex: 9999,
                            opacity: 0,
                            helper: function (event) {
                                var toReturn = $('<div id="' + uniqueId + 'Clone" class="LayoutHandleClone" data-handle="left" data-y_impact="' + $(this).parent().data("y_impact") + '" data-x_impact="' + $(this).parent().data("x_impact") + '" data-axis="x" style="z-index:' + (7500 + layoutHandlesCounter) + '"></div>');
                                return toReturn;
                            },
                            start: $.fn.AdminSettingsLayoutResizeHandleStartDrag,
                            stop: $.fn.AdminSettingsLayoutResizeHandleStopDrag,
                            drag: $.fn.AdminSettingsLayoutResizeHandleDragging
                        }
                        );
                    });
                    break;
            }
            /*#endregion*/
            /*#region rightHandle*/
            switch ($(this).data("resize_axis")) {
                case "x":
                case "xy":
                    htmlBribe = "<div class='ui-icon ui-icon-arrowthick-2-e-w layoutHandleRight layoutHandle' style='z-index:" + (7000 + layoutHandlesCounter) + "'></div>"
                    layoutHandlesCounter++;
                    $(this).append(htmlBribe);
                    $(this).find(".layoutHandleRight").each(function () {
                        $(this).uniqueId();
                        var uniqueId = $(this).attr("id");
                        $(this).draggable(
                        {
                            axis: "x",
                            zIndex: 9999,
                            opacity: 0,
                            helper: function (event) {
                                toReturn = $('<div style="z-index:99999;" id="' + uniqueId + 'Clone" class="LayoutHandleClone" data-handle="right" data-y_impact="' + $(this).parent().data("y_impact") + '" data-x_impact="' + $(this).parent().data("x_impact") + '" data-axis="x" style="z-index:' + (7500 + layoutHandlesCounter) + '"></div>');
                                return toReturn;
                            },
                            start: $.fn.AdminSettingsLayoutResizeHandleStartDrag,
                            stop: $.fn.AdminSettingsLayoutResizeHandleStopDrag,
                            drag: $.fn.AdminSettingsLayoutResizeHandleDragging
                        }
                        );
                    });
                    break;
            }
            /*#endregion*/
            /*#region bottomHandle*/
            switch ($(this).data("resize_axis")) {
                case "y":
                case "xy":
                    htmlBribe = "<div class='ui-icon ui-icon-arrowthick-2-n-s layoutHandleBottom layoutHandle' style='z-index:" + (7000 + layoutHandlesCounter) + "'></div>"
                    layoutHandlesCounter++;
                    $(this).append(htmlBribe);
                    $(this).find(".layoutHandleBottom").each(function () {
                        $(this).uniqueId();
                        var uniqueId = $(this).attr("id");
                        $(this).draggable(
                        {
                            axis: "x",
                            zIndex: 9999,
                            opacity: 0,
                            helper: function (event) {
                                toReturn = $('<div id="' + uniqueId + 'Clone" class="LayoutHandleClone" data-handle="bottom" data-y_impact="' + $(this).parent().data("y_impact") + '" data-x_impact="' + $(this).parent().data("x_impact") + '" data-axis="y" style="z-index:' + (7500 + layoutHandlesCounter) + '"></div>');
                                return toReturn;
                            },
                            start: $.fn.AdminSettingsLayoutResizeHandleStartDrag,
                            stop: $.fn.AdminSettingsLayoutResizeHandleStopDrag,
                            drag: $.fn.AdminSettingsLayoutResizeHandleDragging
                        }
                        );
                    });
                    break;
            }
            /*#endregion*/
            /*#region allHandle*/
            switch ($(this).data("resize_axis")) {
                case "xy":
                    htmlBribe = "<div class='ui-icon ui-icon-arrowthick-2-se-nw layoutHandleAll layoutHandle' style='z-index:" + (7000 + layoutHandlesCounter) + "'></div>"
                    layoutHandlesCounter++;
                    $(this).append(htmlBribe);
                    $(this).find(".layoutHandleAll").each(function () {
                        $(this).uniqueId();
                        var uniqueId = $(this).attr("id");
                        $(this).draggable(
                        {
                            zIndex: 9999,
                            opacity: 0,
                            helper: function (event) {
                                toReturn = $('<div id="' + uniqueId + 'Clone" class="LayoutHandleClone" data-handle="all" data-y_impact="' + $(this).parent().data("y_impact") + '" data-x_impact="' + $(this).parent().data("x_impact") + '" data-axis="xy" style="z-index:' + (7500 + layoutHandlesCounter) + '"></div>');
                                return toReturn;
                            },
                            start: $.fn.AdminSettingsLayoutResizeHandleStartDrag,
                            stop: $.fn.AdminSettingsLayoutResizeHandleStopDrag,
                            drag: $.fn.AdminSettingsLayoutResizeHandleDragging
                        }
                        );
                    });
                    break;
            }
            /*#endregion*/
        });
    }
}

$.fn.AdminSettingsLayoutResizeHandleDragging = function (evt, ui) {//, axis, xImpact, yImpact) {
    /// <summary>
    /// Layout resize handles dragging handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var handle = ui.helper.data("handle");
    var axis = ui.helper.data("axis");
    var xImpact = ui.helper.data("x_impact");
    var yImpact = ui.helper.data("y_impact");
    var newWidth = 0;
    var newHeight = 0;
    var cssValue;
    if (axis == "x" || axis == "xy") {
        if (handle == "left") {
            newWidth = Math.round(LayoutHandlingDragHOriginalWith - (ui.position.left * 2));
        } else { //right or all
            newWidth = Math.round(LayoutHandlingDragHOriginalWith + ((ui.position.left - LayoutHandlingDragHOriginalWith) * 2));
        }
        cssValue = newWidth + "px";
        $("#" + ui.helper.attr("id").replace("Clone", "")).parent().css("width", cssValue);
        $(".LayoutBalloon").find("span.width").text(newWidth + "px");
        eval(xImpact);
    }
    if (axis == "y" || axis == "xy") {
        if (handle == "top") {
            newHeight = Math.round(LayoutHandlingDragVOriginalHeight - (ui.position.top * 2));
        } else {
            newHeight = Math.round(ui.position.top + 16);
        }
        if (newHeight < 0) {
            newHeight = 0;
        }
        var cssValue = newHeight + "px";
        var eltToResize = $("#" + ui.helper.attr("id").replace("Clone", "")).parent();

        eltToResize.css("height", cssValue);
        eltToResize.css("min-height", cssValue);


        $(".LayoutBalloon").find("span.height").text(newHeight + "px");
        eval(yImpact);
    }
    //$.fn.TinyMCEResizeActiveEditor($("#divFooEditor"));
}

$.fn.AdminSettingsLayoutResizeHandleStartDrag = function (evt, ui) {
    /// <summary>
    /// Layout resize handles start drag handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var axis = ui.helper.data("axis");
    var xImpact = ui.helper.data("x_impact");
    var yImpact = ui.helper.data("y_impact");
    if (axis == "x" || axis == "xy") {
        LayoutHandlingDragHOriginalWith = $("#" + $(this).attr("id").replace("Clone", "")).parent().width();
    } else {
        LayoutHandlingDragHOriginalWith = null;
    }
    if (axis == "y" || axis == "xy") {
        LayoutHandlingDragVOriginalHeight = $("#" + $(this).attr("id").replace("Clone", "")).parent().height();
    } else {
        LayoutHandlingDragVOriginalHeight = null;
    }
    $.fn.AdminSettingsLayoutSaveCancelPanelBuild("divFooEditor_innoSiteLayout");
}

$.fn.AdminSettingsLayoutResizeHandleStopDrag = function (evt, ui) {
    /// <summary>
    /// Layout resize handles stop drag handler (Not used)
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
}

$.fn.AdminSettingsLayoutSaveCancelPanelBuild = function (parentItemId) {
    /// <summary>
    /// Add save and cancel disks to the site layout button
    /// </summary>
    /// <param name="parentItemId"></param>
    var parentItem = $("#" + parentItemId);
    $("#divSiteLayoutSaveContainer").remove();
    parentItem.css("display", "block");
    parentItem.css("position", "relative");
    var buttonsHtml = "<div id='divSiteLayoutSaveContainer'><div id='divSiteLayoutSave'><div id='SiteLayoutSave'></div><div id='SiteLayoutCancelSave'></div></div></div>";
    parentItem.append(buttonsHtml);
    $("#SiteLayoutSave").on("click", $.fn.AdminSettingsLayoutSaveLayoutClick);
    var cancelSaveButton = $("#SiteLayoutCancelSave");
    cancelSaveButton.on("click", $.fn.AdminSettingsLayoutCancelLayoutClick);

    cancelSaveButton.data("pageWidth", $("#MyPrettyCMSContent").width());
    cancelSaveButton.data("premenuHeight", $(".premenu").height());
    cancelSaveButton.data("postMenuHeight", $(".postmenu").height());
    cancelSaveButton.data("bodyHeight", $("#MyPrettyCMSContent").height());
}

$.fn.AdminSettingsLayoutShowHideBlockCheckBoxChange = function (evt, ui) {
    /// <summary>
    /// AdminSettingsLayoutShowHideBlockCheckBoxChange
    /// </summary>
    /// <param name="parentItemId"></param>
    ($(this).is(":checked") ? $($(this).parent().data("for")).show() : $($(this).parent().data("for")).hide());
    $.fn.AdminSettingsLayoutSaveCancelPanelBuild("#divFooEditor_innoSiteLayout");
    $.fn.EnsureStopPropagation(evt);
}

$.fn.AdminSettingsLayoutShowHideDialogInputChange = function (evt, ui) {
    $.fn.AdminSettingsLayoutSaveCancelPanelBuild("divFooEditor_innoSiteLayout");
}

$.fn.AdminSettingsLayoutUploadBGMouseEnter = function (evt, ui) {
    /// <summary>
    /// When mouse enter in upload bg image icon
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var parent = $(this).parent();
    $(this).data("previousBGColor", parent.css("background-color"));
    parent.css("background-color", "rgba(255,230,230,0.8)");
}

$.fn.AdminSettingsLayoutUploadBGMouseOut = function (evt, ui) {
    /// <summary>
    /// When mouse leave upload bg image icon 
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    $(this).parent().css("background-color", $(this).data("previousBGColor"));
}

$.fn.AdminSettingsRefreshSample = function (evt, ui) {
    /// <summary>
    /// Refresh the Admin settings Sample iFrame content
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var url = "/AdminSettings/Sample/" + uiLanguage + "?roundedcorners=" + $("#Settings_JQueryCornersRounded").val() + "&jquerytheme=" + $("#Settings_JQueryUITheme").val() + "&kendouitheme=" + $("#Settings_KendoUITheme").val();
    $("#ifrSettingsSample").attr("src", url);
}


$.fn.AdminSettingsSaved = function () {
    /// <summary>
    /// When admin settings saved navigation to /
    /// </summary>
    $.fn.NavigateTo("/");
}

//#endregion

//#region CodeMirror Stuff

$.fn.CodeMirrorBuildCodePanel = function (mode, content) {
    /// <summary>
    /// Prepare the code panel content and build editor
    /// </summary>
    /// <param name="mode"></param>
    /// <param name="content"></param>
    var cp = $("#divCodePanel");
    if (cp.length == 0) {
        cp = $("body").append("<div id='divCodePanel' class='CodePanel'><div id='resizeN'><div class='ui-icon ui-icon-close codePanelCloseButton'></div></div><div id='divCodeMirrorCont'></div></div>");
        $("#resizeN").on("click", $.fn.CodeMirrorCodePanelRemove);
        var wh = $(window).height();
        //$.fn.WriteStatus(wh);
    }
    cmEditor = CodeMirror($("#divCodeMirrorCont")[0],
        {
            value: content,
            mode: mode,
            lineWrapping: true,
            lineNumbers: true,
            tabMode: "indent"
        }
    );
    var totalLines = cmEditor.lineCount();
    var totalChars = cmEditor.getValue().length;
    cmEditor.autoFormatRange({ line: 0, ch: 0 }, { line: totalLines, ch: totalChars });
    cmEditor.setSize(null, "180px");
    cmInitialContent = content;
    cmEditor.on("change", $.fn.CodeMirrorChange);
    cmEditor.setCursor(0, 0);
}

$.fn.CodeMirrorBuildCodePanelCSSEditor = function (a) {
    /// <summary>
    /// Cancel save CodeMirror modifications click handler
    /// </summary>
    /// <param name="a">Ajax Result Data object</param>
    if (a.success) {
        cmWhat = "css";
        cmSourceObj: "ajax:css";
        $.fn.CodeMirrorRemoveObjects();
        $.fn.CodeMirrorBuildCodePanel("css", a.cssContent);
    }
}

$.fn.CodeMirrorCodePanelRemove = function () {
    /// <summary>
    /// Remove the code panel and ask to save if necessary
    /// </summary>
    var cs = $("#divCodeSave");
    if (cs.length > 0) {
        $.fn.jqDialogYesNoFunction(cap_CodeMirrorChanged_Title, cap_CodeMirrorChanged, cap_YesButtonCaption, cap_NoButtonCaption, $.fn.CodeMirrorDialogApplyChangesAndRemoveCodePanel, $.fn.CodeMirrorDialogCancelChange, $.fn.CodeMirrorDialogOpen, 450, 150);
    } else {
        $.fn.CodeMirrorSaveCancelPanelRemove();
        $("#divCodePanel").remove();
        $(this).remove();
    }
}

$.fn.CodeMirrorCSSSaved = function (a) {
    /// <summary>
    /// Occurs when CSS has been saved
    /// </summary>
    /// <param name="a">Ajax Result Data object</param>

    //ToDo : Check if a.success must be tested

    cmChanged = false;
    //$.fn.jqDialogAlert('My Pretty CMS', a.message, '', 450, 300);
    reloadStyleQueryString = '?reload=' + new Date().getTime();
    $('link[rel="stylesheet"]').each(function () {
        if (this.href.toLowerCase().indexOf("site") >= 0) {
            var href = this.href;
            href = href.replace(/\?.*|$/, reloadStyleQueryString);
            this.href = href;
        }
    });
}

$.fn.CodeMirrorDialogApplyChanges = function (evt, ui) {
    /// <summary>
    /// Displays CodeMirror apply change Dialog
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>

    //ToDo : Check behavior

    switch (cmWhat) {
        case "js":
            $.fn.jqDialogAlert(cap_DialogErrorTitle, cap_NotImplemented, '', 250, 300);
            break;
        case "css":
            $.fn.CodeMirrorSaveCSS();
            break;
        case "html":
            $.fn.CodeMirrorSaveHTML();
            break;
    }
    if ($(this).dialog != null) {
        $(this).dialog("close");
    }
    $.fn.EnsureStopPropagation(evt);
    return false;
}

$.fn.CodeMirrorDialogApplyChangesAndRemoveCodePanel = function (evt, ui) {
    /// <summary>
    /// Apply code mirror changes
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    $.fn.CodeMirrorDialogApplyChanges(evt, ui);
    $(this).dialog("close");
}

$.fn.CodeMirrorDialogCancelChange = function (evt, ui) {
    /// <summary>
    /// Cancel CodeMirror changes
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>    
    cmChanged = false;
    cmEditor.setValue("");
    var cp = $("#divCodePanel");
    if (cp.length != 0) {
        cp.remove();
    }
    $(this).dialog("close");
    $.fn.CodeMirrorSaveCancelPanelRemove();
    $.fn.EnsureStopPropagation(evt);
}

$.fn.CodeMirrorDialogOpen = function (evt, ui) {
    /// <summary>
    /// Code mirror apply change Dialog Open handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>    
    $(this).parent().children().children('.ui-dialog-titlebar-close').hide();
}

$.fn.RibbonCodeMirrorCSSSourceClick = function (evt) {
    /// <summary>
    /// Ribbon button click handler : CodeMirror CSS Source edition
    /// </summary>
    /// <param name="evt"></param>
    var cp = $("#divCodePanel");
    $.fn.CodeMirrorRemoveObjects();
    $.fn.CodeMirrorLoadCSS(evt);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.RibbonCodeMirrorHTMLSourceClick = function (evt) {
    /// <summary>
    /// Ribbon button click handler : CodeMirror HTML Source edition
    /// ToDo LJO : Improve HTML Source edition to limit content to layoutSlots content
    /// </summary>
    /// <param name="evt"></param>
    $.fn.CodeMirrorRemoveObjects();
    cmWhat = "html";
    var content = $("#divContent").html();
    $.fn.CodeMirrorBuildCodePanel("htmlmixed", content);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.CodeMirrorLoadCSS = function (evt) {
    /// <summary>
    /// Request CSS content
    /// </summary>
    var url = "/locapi/" + $("#hidLanguage").val() + "/CssEdition/Get";
    $.ajax(
    {
        type: "GET",
        url: url,
        data: null,
        contentType: "application/json",
        async: false,
        success: $.fn.CodeMirrorBuildCodePanelCSSEditor,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAjaxError(cap_DialogErrorTitle, (xhr.responseText));
        }
    });
    $.fn.EnsureStopPropagation(evt);
}

$.fn.CodeMirrorPanelRemove = function () {
    ///<summary>
    /// Close verify is code panel is changed
    /// If yes : Ask for keep changes
    /// If no  : close it
    ///</summary>
    ///<returns>true if the code can continue, false if not</returns>
    var toReturn = true;
    var cp = $("#divCodePanel");
    if (cp.length > 0) {
        if (cmChanged) {
            $.fn.jqDialogYesNoFunction(cap_CodeMirrorChanged_Title, cap_CodeMirrorChanged, cap_YesButtonCaption, cap_NoButtonCaption, $.fn.CodeMirrorDialogApplyChangesAndRemoveCodePanel, $.fn.CodeMirrorDialogCancelChange, $.fn.CodeMirrorDialogOpen, 450, 150);
            toReturn = false;
            return toReturn;
        }
        if (cp.length != 0) {
            $.fn.CodeMirrorRemoveObjects();
        }
    }
    return toReturn;
}


$.fn.CodeMirrorRemoveObjects = function () {
    /// <summary>
    /// Code mirror remove objects 
    /// </summary>
    //Remove save and cancel button
    $.fn.CodeMirrorSaveCancelPanelRemove();
    //RemoveCodePanel
    var cp = $("#divCodePanel");
    if (cp.length > 0) {
        cp.remove();
    }
}

$.fn.CodeMirrorResizeCodePanel = function (newTop) {
    /// <summary>
    /// Manage CodeMirror resizing (Disabled for 1st release)
    /// </summary>
    /// <param name="newTop"></param>
    if (!codePannelResizing) {
        codePannelResizing = true;
        var windowHeight = $(window).height();
        var sizer = $("#resizeN");
        var cp = $("#divCodePanel");
        var currentHeight = cp.height();
        var newHeight = newTop - sizer.height();
        cp.height(newHeight);
        cp.css("top", (windowHeight - newHeight) + "px");
        /*
        var cmCont = $("#divCodeMirrorCont");
        var divCodePanel = $("#divCodePanel");
        var newHeight = $(window).height() - sizer.offset().top;
        divCodePanel.css("height", newHeight);
        sizer.css("top", 0);
        cmCont.height(divCodePanel.height() - sizer.height());
        cmEditor.setSize(cmCont.width() - 22, "100%");
        */
        codePannelResizing = false;
    }
}

$.fn.CodeMirrorSaveCancelPanelBuild = function (parentItem) {
    /// <summary>
    /// Add save and cancel disks to the Code edition button
    /// </summary>
    /// <param name="parentItem"></param>
    $("#divCodeSaveContainer").remove();
    parentItem.css("display", "block");
    parentItem.css("position", "relative");
    var buttonsHtml = "<div id='divCodeSaveContainer'><div id='divCodeSave'><div id='CodeEditorSave'></div><div id='CodeEditorCancelSave'></div></div></div>";
    parentItem.append(buttonsHtml);
    $("#CodeEditorSave").bind("click", $.fn.CodeMirrorSaveCode);
    $("#CodeEditorCancelSave").bind("click", $.fn.CodeMirrorCancelSaveCode);
}

$.fn.CodeMirrorSaveCancelPanelRemove = function () {
    /// <summary>
    /// Hide CodeMirror container
    /// </summary>
    $("#divCodeSaveContainer").remove();
}

$.fn.CodeMirrorSaveCode = function (evt, ui) {
    /// <summary>
    /// Save code button event handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>    
    switch (cmWhat) {
        case "js":
            //NotImplementedYet
            break;
        case "css":
            $.fn.CodeMirrorSaveCSS(evt, ui);
            break;
        case "html":
            $.fn.CodeMirrorSaveHTML(evt, ui);
            break;
    }
}

$.fn.CodeMirrorSaveCSS = function () {
    /// <summary>
    /// Code mirror Save CSS request
    /// </summary>
    SaveCss_JSonModel.cssContent = cmEditor.getValue();
    ajaxData = JSON.stringify(SaveCss_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/api/CssEdition/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.CodeMirrorCSSSaved, //CSSSaved called by the server
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAjaxError(cap_DialogErrorTitle, xhr.responseText);
        }
    });
    return false;
}

$.fn.CodeMirrorSaveHTML = function () {
    /// <summary>
    /// Transferts CodeMirror content to page
    /// </summary>
    var newContent = cmEditor.getValue();
    $("#divContent").html(newContent);
    cmChanged = false;
}

//#endregion

//#region Structure edition stuff

$.fn.StructureEditorMenuItemAddEditDialog = function (evt) {
    savedEvt = evt;
    var el = $(this);
    var layoutMenuTranslationId = -1; //-1 for add mode
    if (el.hasClass("EditMenuItem")) {
        layoutMenuTranslationId = el.attr("data-id");
    }
    LayoutMenuItemFeed_JSonModel.HtmlElementToUpdate = "#divMnuItmEdt";
    LayoutMenuItemFeed_JSonModel.DirectURL = el.attr("data-DirectURL");
    LayoutMenuItemFeed_JSonModel.LayoutMenu_Translation_Id = layoutMenuTranslationId = el.attr("data-id");
    //MVC4 Razor Null<int> rendering
    var parentMenuId = el.attr("data-LayoutMenuTranslationLayoutMenuParent");
    LayoutMenuItemFeed_JSonModel.LayoutMenuTranslationLayoutMenuParent = (parentMenuId == 0 ? null : parentMenuId);

    ajaxData = JSON.stringify(LayoutMenuItemFeed_JSonModel);
    $.ajax(
        {
            type: "POST",
            url: "/DynaStructure/LayoutMenuItemFeed/" + uiLanguage,
            data: ajaxData,
            contentType: "application/json",
            async: false,
            success: $.fn.StructureEditorMenuItemEditDialogFeed,
            error: function (xhr, ajaxOptions, thrownError) {
                $.fn.jqDialogAjaxError(cap_DialogErrorTitle, (xhr.responseText));
            }
        });
    $.fn.EnsureStopPropagation(evt);
}

$.fn.StructureEditorMenuItemEditDialogFeed = function (a, b, c) {
    if (a.success) {
        $.fn.jqDialogFunction("divMnuItmEdt", cap_EditMenuItem, $.fn.StructureEditorMenuItemAddEdit, null, $.fn.StructureEditorPrepareMnuItmEdt, null, null, a.htmlContent, false, true);
    } else {
        eval(a.scriptToExecute);
    }
}

$.fn.StructureEditorMenuItemAddEdit = function () {
    var form = $("#frmMnuItmEdt");
    if (form.valid()) {
        //Join friendlyURL
        for (var i = 0; i < tLanguages.length; i++) {
            var directURL = "/" + $("#Translations_" + i + "__Language_Language").val() + "/"
                + ($("#Translations_" + i + "__Ancestors").val() == "" ? "" : $("#Translations_" + i + "__Ancestors").val() + "/")
                + $("#Translations_" + i + "__MenuNameURLFormatted").val() + "/"
                + $("#Translations_" + i + "__PageNameURLFormatted").val() + $("#Translations_" + i + "__AdrBldrSuffix").val();
            $("#Translations_" + i + "__DirectURL").val(directURL);
        }
        //This fix a little bug of the ASP.net MVC4 Ajax.BeginForm
        form.attr("action", "/DynaStructure/LayoutMenuItemAddEdit/" + uiLanguage);
        form.submit();
        $(this).dialog("close");
    }
}

$.fn.StructureEditorMenuItemUpdated = function (a, b, c) {
    if (a.success) {
        $(a.domElementToUpdate).html(a.htmlContent);
        if (a.scriptToExecute != null) {
            eval(a.scriptToExecute);
        }
    } else {
        if (a.scriptToExecute != null) {
            eval(a.scriptToExecute);
        }
    }
    if (savedEvt != null) {
        $.fn.EnsureStopPropagation(savedEvt);
    }
}

$.fn.StructureEditorMenuItemRemoveConfirm = function (evt) {
    savedEvt = evt;
    LayoutMenuItemRemove_JSonModel.DirectURL = $(this).attr("data-DirectURL"),
    LayoutMenuItemRemove_JSonModel.LayoutMenu_Translation_Id = $(this).attr("data-id"),
    LayoutMenuItemRemove_JSonModel.LayoutMenuTranslationLayoutMenuParent = $(this).attr("data-LayoutMenuTranslationLayoutMenuParent")
    MenuItemAction = LayoutMenuItemRemove_JSonModel;
    $.fn.jqDialogConfirm(cap_RemoveMenuItemConfirmTitle, cap_RemoveMenuItemConfirmMessage, cap_RemoveMenuItemConfirmOkButtonTitle, cap_RemoveMenuItemConfirmCancelButtonTitle, $.fn.StructureEditorMenuItemRemove, null, null);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.StructureEditorMenuItemRemove = function () {
    $('#dialogMessage').dialog('close');
    ajaxData = JSON.stringify(MenuItemAction);
    $.ajax(
    {
        type: "POST",
        url: "/DynaStructure/LayoutMenuItemRemoveItem/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.StructureEditorMenuItemUpdated,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, (xhr.responseText));
        }
    });
}

$.fn.StructureEditorMenuItemMove = function (evt) {
    savedEvt = evt;
    LayoutMenuItemMove_JSonModel.DirectURL = $(this).attr("data-DirectURL");
    LayoutMenuItemMove_JSonModel.LayoutMenu_Translation_Id = $(this).attr("data-id");
    LayoutMenuItemMove_JSonModel.LayoutMenuTranslationLayoutMenuParent = $(this).attr("data-LayoutMenuTranslationLayoutMenuParent");
    LayoutMenuItemMove_JSonModel.Direction = $(this).attr("data-value");
    ajaxData = JSON.stringify(LayoutMenuItemMove_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/DynaStructure/LayoutMenuItemMove/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.StructureEditorMenuItemUpdated,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
    return false;
}

$.fn.StructureEditorPrepareMnuItmEdt = function (evt, ui) {
    /// <summary>
    /// Finalize menu item dialog
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var loops = tLanguages.length;
    for (var i = 0; i < loops; i++) {
        if ($("#Translations_" + i + "__SortIndex").val() == "1" && $("#Translations_" + i + "__LayoutMenuTranslationLayoutMenuParent").val() == "") {
            $(".hiddenForIndex").addClass("notDisplayed");
            $(".tblFinalUrl").css("width", "");
        } else {
            $(".hiddenForIndex").removeClass("notDisplayed");
            $(".tblFinalUrl").css("width", "600px");
        }
    }
    if (!($("#SortIndex").val() == "1" && $("#FK_LayoutMenu").val() == "")) {
        $.fn.StructureEditorPrepareFriendURL();
    }
}

$.fn.StructureEditorPrepareFriendURL = function () {
    var languageCount = tLanguages.length;
    var chineseIndex = -1;
    for (var i = 0; i < languageCount; i++) {
        if (tLanguages[i] != "zh-cn") {
            $("#Translations_" + i + "__PageTitle").friendurl({ id: "Translations_" + i + "__PageNameURLFormatted", divider: '_', transliterate: false });
            $("#Translations_" + i + "__ButtonCaption").friendurl({ id: "Translations_" + i + "__MenuNameURLFormatted", divider: '_', transliterate: false });
        } else {
            chineseIndex = i;
            $("#Translations_zh_cn__PageTitle").friendurl({ id: "Translations_" + chineseIndex + "__PageNameURLFormatted", divider: '_', transliterate: false });
            $("#Translations_zh_cn__ButtonCaption").friendurl({ id: "Translations_" + chineseIndex + "__MenuNameURLFormatted", divider: '_', transliterate: false });
        }
    }
}

$.fn.StructureEditorToggleMenuActivation = function () {
    /// <summary>
    /// Activates or deactivate the menu
    /// </summary>
    $('#dialogMessage').dialog('close');
    ajaxData = JSON.stringify(MenuItemAction);
    $.ajax(
    {
        type: "POST",
        url: "/DynaStructure/ToggleActivation/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.StructureEditorMenuItemUpdated,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, (xhr.responseText));
        }
    });
}

$.fn.StructureEditorToggleActivationConfirmation = function (evt, ui) {
    /// <summary>
    /// Occurs when user click on the activation button of a menu
    /// ToDo : LJO ask if all language must be activated in the same operation
    /// </summary>
    /// <param name="evt"></param>
    savedEvt = evt;
    LayoutMenuItemToggleActivation_JSonModel.DirectURL = $(this).attr("data-DirectURL");
    LayoutMenuItemToggleActivation_JSonModel.LayoutMenu_Translation_Id = $(this).attr("data-id");
    LayoutMenuItemToggleActivation_JSonModel.LayoutMenuTranslationLayoutMenuParent = $(this).attr("data-LayoutMenuTranslationLayoutMenuParent")
    MenuItemAction = LayoutMenuItemToggleActivation_JSonModel;
    var newStatus = "";
    if ($(this).hasClass("AdminModeMenuToggleActivationOn")) {
        newStatus = cap_ToggleMenuActivationNewStatus_Disabled;
    } else {
        newStatus = cap_ToggleMenuActivationNewStatus_Enabled;
    }
    $.fn.jqDialogConfirm(cap_ToggleMenuActivationTitle, cap_ToggleMenuActivationMessage + newStatus, cap_ToggleMenuActivationOkButtonTitle, cap_ToggleMenuActivationCancelButtonTitle, $.fn.StructureEditorToggleMenuActivation, null, null);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.SetController = function (evt, ui) {
    /// <summary>
    /// Controller drop down selection handling
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    //ToDo verify if used
    $.fn.EnsureStopPropagation(evt);
    $.fn.SetControllerTextBoxValue($(this));
}

$.fn.SetControllerTextBoxValue = function (ddl) {
    /// <summary>
    /// Transfert Controller selection to the right textbox
    /// </summary>
    /// <param name="ddl"></param>
    var fieldset = ddl.closest("fieldset");
    var LanguageIndex = fieldset.find("select").attr("LanguageIndex");
    var ControllerTextBoxId = "Menus_" + LanguageIndex + "__Controller";
    var ControllerTextBox = $("#" + ControllerTextBoxId);
    var val = ddl.val();
    ControllerTextBox.val(val);
    //    if (val != "") {
    //        ControllerTextBox.attr("readonly", "readonly");
    //        ControllerTextBox.addClass("readonly");
    //    } else {
    //        ControllerTextBox.removeAttr("readonly");
    //        ControllerTextBox.removeClass("readonly");
    //    }
}
//#endregion

//#region Settings Users stuff

$.fn.SettingsUsersDialog = function () {
    /// <summary>
    /// Prepare and open MyProfile AdminUsers dialog
    /// </summary>
    $.fn.jqDialogContainer("AdminDivDialogUsers", cap_Settings_AdminUsers, $.fn.SettingsUsersBuildAdminUsersGrid, null, 1100, 540, "<div id='AdminDivDialogUsersGrid'></div>");
}

$.fn.SettingsUsersBuildAdminUsersGrid = function () {
    /// <summary>
    /// Build MyProfile AdminUsers grid
    /// </summary>
    $("#AdminDivDialogUsersGrid").css("overflow", "hidden");
    $("#AdminDivDialogUsersGrid").kendoGrid($.fn.SettingsUsersPrepareAdminUsersGrid());
}

$.fn.SettingsUsersPrepareAdminUsersGrid = function () {
    var toReturn = {
        dataSource: $.fn.SettingsUsersPrepareAdminUsersGridDataSource(),
        height: 425,
        filterable: true,
        sortable: true,
        selectable: true,
        pageable: { messages: { display: "{0:d0} - {1:d0} " + cap_KendoUIGrid_Pageable_Of + " {2:d0} " + cap_KendoUIGrid_Pageable_Elements } },
        columns: [
            {
                field: "UserId",
                filterable: false,
                hidden: true
            },
            {
                field: "FavoriteLanguage",
                title: Ety_v_AdminUsers_FavoriteLanguage,
                filterable: true,
                width: 55,
                template: "<span class='dataId' data-id='#= UserId #'>#= FavoriteLanguage #</span>"
            },
            {
                field: "Username",
                title: Ety_v_AdminUsers_Username,
                filterable: true,
                width: 100
            },
            {
                field: "Email",
                title: Ety_v_AdminUsers_EMail,
                filterable: true,
                width: 150
            },
            {
                field: "IsApproved",
                title: Ety_v_AdminUsers_IsApproved,
                filterable: true,
                width: 50
            },
            {
                field: "IsOnline",
                title: Ety_v_AdminUsers_IsOnline,
                filterable: true,
                width: 50
            },
            {
                field: "IsLockedOut",
                title: Ety_v_AdminUsers_IsLockedOut,
                filterable: true,
                width: 50
            },
            {
                field: "Genre",
                title: Ety_v_AdminUsers_Genre,
                filterable: true,
                width: 50
            },
            {
                field: "FirstName",
                title: Ety_v_AdminUsers_FirstName,
                filterable: true,
                width: 175
            },
            {
                field: "LastName",
                title: Ety_v_AdminUsers_LastName,
                filterable: true,
                width: 175
            },
            {
                command: {
                    name: "edt",
                    click: $.fn.SettingsUsersBuildUserEditDialog
                },
                title: "",
                width: 85
            },
            {
                command: {
                    name: "X",
                    click: $.fn.SettingsUsersConfirmDelete
                },
                title: "",
                width: 85
            }
        ]
    };
    return toReturn;
}

$.fn.SettingsUsersPrepareAdminUsersGridDataSource = function () {
    /// <summary>
    /// Prepare MyProfile AdminUsers grid data source
    /// </summary>
    var toReturn = new kendo.data.DataSource({
        type: "odata",
        serverPaging: true,
        serverSorting: true,
        pageSize: 10,
        transport:
        {
            read:
            {
                url: "/odata/adminusers",
                dataType: "json"
            }
        },
        schema:
        {
            data: function (data) {
                return data["value"];
            },
            total: function (data) {
                return data["odata.count"];
            },
            model: {
                fields: {
                    UserId: { type: "uid" },
                    FavoriteLanguage: { type: "string" },
                    Username: { type: "string" },
                    Email: { type: "string" },
                    IsApproved: {
                        type: "boolean",
                        parse: $.fn.KenduUINullableBoolColumnParser,
                        nullable: true
                    },
                    IsOnline: {
                        type: "boolean",
                        parse: $.fn.KenduUINullableBoolColumnParser,
                        nullable: true
                    },
                    IsLockedOut: {
                        type: "boolean",
                        parse: $.fn.KenduUINullableBoolColumnParser,
                        nullable: true
                    },
                    Genre: { type: "string" },
                    FirstName: { type: "string" },
                    LastName: { type: "string" }
                }
            }
        }
    });
    toReturn.bind("error", $.fn.KendoDataSourceError);
    toReturn.fetch();
    return toReturn;
}

$.fn.SettingsUsersBuildUserEditDialog = function (evt) {
    /// <summary>
    /// Build Admin User Edit Dialog
    /// </summary>
    /// <param name="evt"></param>
    evt.preventDefault();
    var realId = $(evt.currentTarget).closest("tr").find(".dataId").data("id");
    AdminUser_JSonModel.Id = realId;
    AdminUser_JSonModel.HtmlElementToUpdate = "#AdminDivDialogUsersEdit";
    $.fn.jqDialogFunction("AdminDivDialogUsersEdit", cap_Settings_AdminUsers_EditFormTitle, $.fn.AdminSettingsAdminUserOkClick, null, $.fn.SettingsUsersBuildUserRequestFeedEditDialog, 750, 660, null, false, true);
}

$.fn.SettingsUsersConfirmDelete = function (e) {
    /// <summary>
    /// Settings user Confirm user deletion
    /// </summary>
    /// <param name="e"></param>
    e.preventDefault();
    var realId = $(evt.currentTarget).closest("tr").find(".dataId").data("id");
    AdminUser_JSonModel.Id = realId;
    AdminUser_JSonModel.HtmlElementToUpdate = null;
    $.fn.jqDialogConfirm(cap_RemoveMenuItemConfirmTitle, cap_RemoveMenuItemConfirmMessage, cap_RemoveMenuItemConfirmOkButtonTitle, cap_RemoveMenuItemConfirmCancelButtonTitle, $.fn.SettingsUsersDelete, null, null);
}

$.fn.SettingsUsersDelete = function () {
    /// <summary>
    /// User delete request
    /// </summary>
    var ajaxData = JSON.stringify(AdminUser_JSonModel);
    $.ajax(
        {
            type: "POST",
            url: "/Admin/ContactUserDelete/" + uiLanguage,
            data: ajaxData,
            contentType: "application/json",
            async: false,
            success: $.fn.SettingsUsersDialog,
            error: function (xhr, ajaxOptions, thrownError) {
                $.fn.jqDialogAjaxError(cap_DialogErrorTitle, (xhr.responseText));
            }
        });
}

$.fn.SettingsUsersBuildUserRequestFeedEditDialog = function () {
    /// <summary>
    ///AdminUser_JSonModel set in the click 
    /// </summary>
    var ajaxData = JSON.stringify(AdminUser_JSonModel);
    $.ajax(
        {
            type: "POST",
            url: "/Admin/UserItemFeed/" + uiLanguage,
            data: ajaxData,
            contentType: "application/json",
            async: false,
            success: $.fn.SettingsUsersBuildUserFeedEditDialog,
            error: function (xhr, ajaxOptions, thrownError) {
                $.fn.jqDialogAjaxError(cap_DialogErrorTitle, (xhr.responseText));
            }
        });
}

$.fn.SettingsUsersBuildUserFeedEditDialog = function (a, d, c) {
    /// <summary>
    /// SettingsUsersBuildUserRequestFeedEditDialog request result handler
    /// </summary>
    /// <param name="a"></param>
    /// <param name="d"></param>
    /// <param name="c"></param>
    if (a.success) {
        ForUserId = a.additionalData.forUserId;
        $(a.domElementToUpdate).html(a.htmlContent);
        //$(".datePickUp").datepicker();
        //var form = $("#frmMyProfile");
        //$(".MyProfileAddressButton").button();
        //$("#cmdMyProfileAddressAction").on("click", $.fn.ProfileDetailAddressOkClick);
        //$("#cmdMyProfileAddressCancelAction").on("click", $.fn.MyProfileAddressCancelClick);
        //$("#chkDisplayText").on("click", $.fn.ToggleDisplayText);
        var iconUploadDialogOpenButton = $("#UserProfileIconImgUploadButton");
        iconUploadDialogOpenButton.on("click", $.fn.ProfileDetailUserIconUploadDialogOpenClick);
        $.fn.ProfileDetailPrepareButtons(AdminUser_JSonModel.Id, "AdminDivDialogUsersEdit");
    } else {
        if (a.message != null) {
            var messageTitle = cap_DialogErrorTitle;
            if (a.messageTitle != null) {
                messageTitle = a.messageTitle
            }
            $.fn.jqDialogAlert(messageTitle, a.message, null, 400, 300);
        }
    }
}

//#endregion

//#region Settings roles stuff

$.fn.SettingsAdminRolesDialog = function () {
    /// <summary>
    /// Prepare and open MyProfile AdminRoles dialog
    /// </summary>
    /// $.fn.MyProfileBuildAdminRolesDisplayGrid in _layout.js
    $.fn.jqDialogContainer("MyProfileDivDialogSettingsAdminRoles", cap_Settings_AdminRoles, $.fn.MyProfileBuildAdminRolesDisplayGrid, null, 300, 460, "<div id='MyProfileDivDialogSettingsAdminRolesGrid'></div>");
}

$.fn.SettingsAdminRolesPrepareDataSource = function () {
    /// <summary>
    /// Prepare MyProfile AdminRoles grid data source
    /// </summary>
    var toReturn = new kendo.data.DataSource({
        type: "odata",
        serverPaging: true,
        serverSorting: true,
        pageSize: 10,
        transport:
        {
            read:
            {
                url: "/odata/adminroles",
                dataType: "json"
            }
        },
        schema:
        {
            data: function (data) {
                return data["value"];
            },
            total: function (data) {
                return data["odata.count"];
            },
            model: {
                fields: {
                    Id: { type: "number" },
                    Name: { type: "string" }
                }
            }
        }
    });
    toReturn.bind("error", $.fn.KendoDataSourceError);
    toReturn.fetch();
    return toReturn;
}

$.fn.SettingsAdminRolesPrepareGrid = function () {
    /// <summary>
    /// Prepares Admin roles grid
    /// </summary>
    /// <returns type=""></returns>
    var toReturn = {
        dataSource: $.fn.SettingsAdminRolesPrepareDataSource(),
        height: 350,
        filterable: true,
        sortable: true,
        pageable: { messages: { display: "{0:d0} - {1:d0} " + cap_KendoUIGrid_Pageable_Of + " {2:d0} " + cap_KendoUIGrid_Pageable_Elements } },
        columns: [
            {
                field: "Id",
                filterable: false,
                hidden: true
            },
            {
                field: "Name",
                title: Ety_v_AdminRoles_Name,
                filterable: true,
                width: 45,
                template: "<span class='dataId' data-id='#= Id #'>#= Name #</span>"
            }
        ]
    };
    return toReturn;
}

//#endregion
